Sunday, October 30, 2022

Perl loop assignment solved

 In this exercise, you will need to loop through and print out all even numbers from the @NUMBERS array in the same order they are received. Don't print any numbers that come after 237 in the array.

 

@NUMBERS = (951,402,984,651,360,69,408,319,601,485,980,507,725,547,544,615,83,165,141,501,263,617,865,575,219,390,237,412,566,826,248,866,950,626,949,687,217,815,67,104,58,512,24,892,894,767,553,81,379,843,831,445,742,717,958,609,842,451,688,753,854,685,93,857,440,380,126,721,328,753,470,743,527);


for($i=0;($i<=$#NUMBERS);$i+=1) {
if ($NUMBERS[$i]==237)
{
last;
}
if ($NUMBERS[$i]%2==0)
{
print $NUMBERS[$i]."\n";
}


Perl way


@NUMBERS = (951,402,984,651,360,69,408,319,601,485,980,507,725,547,544,615,83,165,141,501,263,617,865,575,219,390,237,412,566,826,248,866,950,626,949,687,217,815,67,104,58,512,24,892,894,767,553,81,379,843,831,445,742,717,958,609,842,451,688,753,854,685,93,857,440,380,126,721,328,753,470,743,527);

foreach $number (@NUMBERS) {
    if ($number % 2 == 0) {
        print $number . "\n";
    }
    last if ($number == 237);
}

Perl Assignment solved using array and hash

 An array @family holds a list of family member names. The first hash %shoe_color contains favorite shoe color per person name. The second hash %shoe_size contains shoe size per person name.

Evaluate and print the favorite shoe color and shoe size per each family member. For shoe sizes 10 and above, add the word 'large' to the output line.

Output lines should be in the format: "Homer wears large brown shoes size 12".

Note: not all family members may be included in the hash variables, so you better conditionally check if they exist or not (using the exists operator). If a name does not exist, add the key/value pair into the hash variables - for show color add: black; for shoe size add 99.

Solution

@family = ('Homer', 'Moe', 'Maggie');
%shoe_color = ('Lisa' => 'red', 'Homer' => 'brown', 'Maggie' => 'pink', 'Marge' => 'blue', 'Bart' => 'yellow');
%shoe_size = ('Moe' => 9, 'Lisa' => 7, 'Homer' => 12, 'Bart' => 8, 'Maggie' => 4);

$default_shoe_color = "black";
$default_shoe_size = 4;

$member = $family[0];
if (!exists $shoe_color{$member}) {
    $shoe_color{$member} = $default_shoe_color;
}
if (!exists $shoe_size{$member}) {
    $shoe_size{$member} = $default_shoe_size;
}
$is_large = ($shoe_size{$member} >= 10) ? " large " : " ";
print "$member wears$is_large$shoe_color{$member} shoes size $shoe_size{$member}\n";

$member = $family[1];
if (!exists $shoe_color{$member}) {
    $shoe_color{$member} = $default_shoe_color;
}
if (!exists $shoe_size{$member}) {
    $shoe_size{$member} = $default_shoe_size;
}
$is_large = ($shoe_size{$member} >= 10) ? " large " : " ";
print "$member wears$is_large$shoe_color{$member} shoes size $shoe_size{$member}\n";

$member = $family[2];
if (!exists $shoe_color{$member}) {
    $shoe_color{$member} = $default_shoe_color;
}
if (!exists $shoe_size{$member}) {
    $shoe_size{$member} = $default_shoe_size;
}
$is_large = ($shoe_size{$member} >= 10) ? " large " : " ";
print "$member wears$is_large$shoe_color{$member} shoes size $shoe_size{$member}\n";

Perl assignment solved using array and hash

 Assign the hash variable called car_catalog to include the following car models and their showroom prices in dollars. Use the car model name as the hash key. The cars and prices are:

    Model: BMW Series 5, price: 100000
    Model: Mercedes 2000, price: 250000
    Model: Toyota Corolla, price: 20000
    Model: Lexus 3, price: 95000

Assign an array variable called my_wishlist with the two cars you want to buy: the first array element is the full model name of the BMW car and the second array model is the full model name of the Toyota car. Use the array variable contents as keys to the hash variable in order to print lines in the following format: "I would like to buy one for the price of Dollars."

Solution

%car_catalog = ("BMW Series 5" => 100000 , "Mercedes 2000" => 250000, "Toyota Corolla" => 20000,"Lexus 3"=>95000);
@my_wishlist = ("BMW Series 5","Toyota Corolla");
print "I would like to buy one $my_wishlist[0] for the price of $car_catalog{$my_wishlist[0]} Dollars.\n";
print "I would like to buy one $my_wishlist[1] for the price of $car_catalog{$my_wishlist[1]} Dollars.\n";

 

 

Source:https://www.learn-perl.org/en/Variables_and_Types

Array and hash example in perl

 @item_price_list = (5 , 8 , 24);
@item_name_list = ("Apple", "Banana", "Mushroom");
print "The price of one $item_name_list[0] is $item_price_list[0] gold coins.\n";
print "The price of one $item_name_list[1] is $item_price_list[1] gold coins.\n";
print "The price of one $item_name_list[2] is $item_price_list[2] gold coins.\n";


%item_catalog = ("Apple" => 5 , "Banana" => 8, "Mushroom" => 24);
# note the required backslash to escape the double-quotes around the key string Apple
print "The price of one Apple is $item_catalog{\"Apple\"} gold coins.\n";
$item_name = "Banana";
print "The price of one $item_name is $item_catalog{$item_name} gold coins.\n";
@item_name_list = ("Apple", "Banana", "Mushroom");
print "The price of one $item_name_list[2] is $item_catalog{$item_name_list[2]} gold coins.\n";


Friday, October 21, 2022

Calculate the area of a right angle triangle using a package in perl

 

package Triangle;   # class name

sub new {
  my $class = shift;
  my $self = {
      _length => shift,
      _height => shift,
  };

 

  # Print all the values just for clarification.
  print "Length is $self->{_length}\n";
  print "Height is $self->{_height}\n";
  bless $self, $class;
  return $self;
}

sub area{
    my ($self) = @_;
    return ($self->{_length} * $self->{_height}) / 2;
  }

1;

$object = new Triangle( 4, 5);
print "Area of Triangle: " . $object->area();

Thursday, October 20, 2022

Sorting array of numbers in perl

 

@numbers = (13, 9, 22, 27, 1, 3, -4, 10);
print "Original: @numbers\n\n";

@sorted_numbers = sort { $a <=> $b } @numbers;

print "After sorting: @sorted_numbers";

Sorting array of strings in perl

 

#defining and array
@fruits = ('Rasberry', 'Orange', 'Apricot','Banana', 'Apple','Olive' );

@fruits = sort(@fruits); #applying the sort function
print("@fruits"); #printing the sorted array

matrix assignment in perl

 sub printMat {
  #write the code for making and printing the matrix here
  #use can use \n to move numers to next line in the matrix
  #use " " to add space between numbers in matrix
  #print "Write your code below"; #comment out this line when you start writing cod
  for ($i = 0; $i < 4 ; $i++) {
    for ($j = 0; $j < 4; $j++) {
      if ($i==$j)
      {
        $val=0;
      }
      elsif($j<$i)
      {
        $val=-1;
      }
      else{
        $val=1;
      }
       $comparisonAdjectives[$i][$j] = $val;

    }
  }

  for ($i = 0; $i < 4 ; $i++) {
    for ($j = 0; $j < 4; $j++) {
      if ($comparisonAdjectives[$i][$j]>=0){
          print " ".$comparisonAdjectives[$i][$j]." ";
      }
      else
      {
          print $comparisonAdjectives[$i][$j]." ";
      }
      
    }
    print "\n";
  }
}

printMat();

Multidimensional array in perl

 

@comparisonAdjectives= (["good", "better", "best"],
                        ["bad", "worse", "worst"],
                        ["tall", "taller", "tallest"]);

for ($i = 0; $i < 3 ; $i++) {
    for ($j = 0; $j < 3; $j++) {
        print $comparisonAdjectives[$i][$j] . " ";
    }
    print "\n";
}

Find maximum value from an array using perl

 

 #Returns maximum value from Array passed as parameter
  sub Find_Maximum {

  my @list = @_;

  $max = $list[0];

  for ($i = 1; $i <= $#list; $i++) { #iterate over all the array elements

    if ($list[$i] > $max) {                 #check if current element is greater than the already
      #stored max value
      $max = $list[$i];                     # if yes then update the max value to current element
    }
  }
  return $max;                           #return the maximum value
}#end of Find_Maximum()

@array = (15, 6, 3, 21, 19, 4);
print Find_Maximum (@array);

Find length of an array in perl

 

@fruits = ("Orange", "Grapefruit", "Lemon");#initializing associative array
print "Length of fruits array is " . scalar(@fruits);

Shift and Unshift in perl

 

@alphabets = (a .. f);

print "Original: @alphabets \n";
shift (@alphabets);   # removing first element of the array

print "Removing first element from an array: @alphabets\n";

unshift (@alphabets, 'a');   # adding last element of the array

print "Adding first element to an array: @alphabets";

push and pop in perl

 @alphabets = (A .. F);

print "Original: @alphabets \n";
push (@alphabets, 'G');   # add G to the last index array

print "Pushing G in the array: @alphabets\n";

pop (@alphabets);   # removing last element of array

print "Removing last element from array: @alphabets\n";
pop (@alphabets);   # removing last element of array

print "Removing last element from array: @alphabets\n\n";

Declare and print an array in perl

 

@fruits = ('Grapes', 'Apple', 'Banana' );

print "@fruits";

Substring in perl

 

$foo = "Hello world";

@arr = split("",$foo);
print $arr[6]; # returns w
print "\n";

print substr($foo, 6, 5); # returns 'world'
 

Finding position of a substring

In Perl, we can use the index method to get the first position/occurrence of a substring

 

 in another string. If the substring does not exist, the index returns -1.

 

 

$str = "The occurence of hay is hay at position:";

print $str . index($str, "hay")."\n";
 

Concatenation of two strings in perl

 

$a = "water";
$b = " bottle";
$c = $a . $b; # $c => water bottle
print $c;
 
 
 
$a = "Hello";
$a .= " World"; # $a => Hello World
print $a;
 

Wednesday, October 19, 2022

Programming assignment in perl

 

sub gpa_Point{
  $grade = @_[0];
 
    if($grade eq "A+")
    {return 4;}
    elsif($grade eq "A")
    { return 4;}
    elsif($grade eq "A-")
    {return 3.7;}
    elsif($grade eq "B+")
    { return 3.3;}
    elsif($grade eq "B")
    { return 3;}
    elsif($grade eq "B-")
    { return 2.8;}
    elsif($grade eq "C+")
    { return 2.5;}
    elsif($grade eq "C")
    { return 2;}
    elsif($grade eq "C-")
    { return 1.8;}
    elsif($grade eq "D")
    { return 1.5;}
    elsif($grade eq "F")
    { return 0;}
    else
    {return -1;}
  }

  print gpa_Point("b-"); # change value to check for multiple grades


Return sum of two numbers using a subroutine in perl

 

sub sum{
   return @_[0] + @_[1];
}

print sum(10, 5);

Pass by reference example in perl

 

sub swap{ #parameters num1 and num2 passed using pass by value method

  $temp = $_[0];   #creating a variable temp and setting equal to $_[0]
  $_[0] = $_[1];  #setting the value of $_[0] equal to $_[1]
  $_[1] = $temp;  #setting the value of $_[1] equal to temp which is equal to $_[0]
}

$num1 = 4;
$num2 = 5;

# Have a careful look at this function call
print "num1 is: $num1\n";
print "num2 is: $num2\n";
print "\nAfter swapping\n\n";

swap($num1,$num2);
print "num1 is: $num1\n";
print "num2 is: $num2";

Pass by value example in perl

 

sub cube {    
  my $num1 = @_[0];     #num1 parameter passed by value here
  return $num1 * $num1 * $num1; #cube of num1 returned
}





$answer = cube(3); #function cube called with 3 passed as the argument
print $answer ;


Subroutine example in perl

 

#subroutine with two parameters
sub mySubroutine{
    $num1 = @_[0];
    $num2 = @_[1];
   
    print  "The value assigned to num1 is $num1\n";
    print  "The value assigned to num2 is $num2";
}
#calling subroutine and passing arguments to it
mySubroutine(3,4);

Local variable and global variable example in perl

 

$number = 20;   # if my is not used then its scope is global

sub foo{
  my $number = 10;  # using my keyword for local variable
  print "Local Variable value" .$number . "\n";
}
foo(); #Will print 10 because text defined inside function is a local variable

print "global Variable value " . $number . "\n";
 
 
 
 
$num1 = 5;  # global variables
$num2 = 2;

sub multiply(){
  $::num1 = 10;
  $::num2 = 20;
  return  $num1 * $num2;
}

# When in the global scope, regular global variables can be used
# without explicitly stating '$::variablename'
print "num1 is: $num1\n";
print "num2 is: $num2\n";
print multiply();
 

Fibonacci sequence in perl

 

#the variable $range contains the number uptil which you need to calculate the fibonacci sequence
# $range is available to you here

$ans = "xyz"; #return the correct string

#write your code for genersting fibonacci sequence here
$i=0,$j=1;
$ans=$i." ".$j;
while(($range-2)>0)
{
$ans=$ans." ".($i+$j);

$j=$i+$j;
$i=$j-$i;
$range--;

}
return $ans;

Multiplication table in perl 5

 

# $num is available as number passed to print the table

# initialize variable to use in while loop

$ans = "xyz"; #return the correct value in this string

#write your code for while loop here
$i=1;
$ans="";
while($i<=10)
{
    $temp=$num*$i;
    $ans.=$temp." ";
    $i+=1;
}

return $ans;