Category Archives: Perl

Example of Functions & Control Structures

Published by:

Example of Multiple Case

#!/usr/bin/perl -w
# $ARGV[0] is expected to be “+” or “-” or “==“

$op = $ARGV[0];

if ($op eq "+") {
	print "Sum";
}
elsif ($op eq "-") {
	print "Difference";
}
elsif ($op eq "==") {
	print "Equality";
}
else {
	print "None of the above";
}

Output:

./multiplecase.sh ==
Equality

While & Regex

 #!/usr/bin/perl -w

# Accepts 3 arguments on the command line:
 # a file to read data from and 2 words.

#Open the file. If an error occurs exit.
 open INFILE, "<$ARGV[0]" or die "error opening file";

while (<INFILE>)
 {
 if (m/b$ARGV[1]b/ && m/^$ARGV[2]/) {
 print $_
 }
 }

Example of Functions

 #!/usr/bin/perl -w

sub max {
 my $max = shift(@_); #takes the first value from the arguments
 print "First value assigned is: " . $max . "n";

foreach $foo (@_) {
 if ($max < $foo) {
 $max = $foo;
 print "Max value changed to: " . $max . "n";
 }
 }
 return $max;
 }

$best = max(7, 8, 9, 10, 6);
 print "The final maximum value is: " . $best;

Output:


First value assigned is: 7
 Max value changed to: 8
 Max value changed to: 9
 Max value changed to: 10
 The final maximum value is: 10

 

Example of Pass by Reference

 #!/usr/bin/perl -w
 $v = 32;
 print ("Value before calling the function: " . $v . "n");
 fun1($v);
 print ("Value after calling the function: " . $v . "n");
 # end of program
 sub fun1
 {
 print ("Value within the function: " . $_[0] . "n");
 $_[0] <<= 1; # shifts all bits left by 1 (like * 2)
 print ("Value within the function, again: " . $_[0] . "n");
 }

Output:


Value before calling the function: 32
 Value within the function: 32
 Value within the function, again: 64
 Value after calling the function: 64

 

Example of Copy Arguments


#!/usr/bin/perl -w
 $v = 32;
 print ("Value before calling the function: " . $v . "n");
 fun1($v);
 print ("Value after calling the function: " . $v . "n");
 # end of program
 sub fun1
 {
 my($local);
 $local = $_[0];
 print ("Value within the function: " . $local . "n");
 $local &= 1; # AND bit by bit between $local and 1:
 # 1 0 0 0 0 0 AND
 # 0 0 0 0 0 1 =
 # 0 0 0 0 0 0
 print ("Value within the function, again: " . $local . "n");
 }

Output:


Value before calling the function: 32
 Value within the function: 32
 Value within the function, again: 0
 Value after calling the function: 32

Perl Control Structures & Subroutines

Published by:

Perl Control Structures

  • statement blocks: {…}
  • if/unless {…} else {…}
  • while/until (expression) {…}
  • do {…} while/until
  • for(start;test;change) {…}
  • foreach $a(list)
  • last – provides a means of jumping out of a loop and continue with the next instruction.
  • next – is a way of jumping to the next iteration in the loop
  • redo – takes you back to the top of the loop block
  • SOME_LABEL: - can be combined with last/next/redo to identify which loop they apply to.

 

Perl Functions

  • A fundamental mechanism in programming languages to encapsulate and re-use code.
  • Functions are:
    • defined
    • called or invoked.
  • Functions:
    • are passed parameters to
    • can return values and or output parameters.
  • Perl calls them subroutines.
  • Can be called with or without arguments; with our without parentheses.
  • Definition:
    
    sub mysubroutine
    
    {
    
    …
    
    …
    
    }
    
    

     

Variables in Subroutines

  • global scope – variables that are visible from anywhere in the program.
  • local variables
    • semilocal or dynamic scope
    • visible in their block but also any functions that get called from it.
  • my variables
    • static or lexical scope
    • visible only from where they are declared to the end of the innermost block.

 

Passing Arguments to a Function

  • Arguments – input parameters to a function
  • Visible from within the function as parameters:
    • @_ (or @ARG) – an array of parameters containing the arguments.
    • for instance, $_[1] is the 2nd argument.
  • Example:
    • function’s invocation: arbit($variable);
    • function’s definition:
      
      sub arbit
      
      {
      
      … $_[0] ...
      
      }
      
      

 

Pass Arguments By Reference or By Value

  • In a Perl function, the arguments are passed to the parameters by reference.
    • Any changes made to a variable by a function persist after the function’s termination.

 

Declare, Define & Call

  • Declaration of, or forward reference to, a subroutine:
    
    sub mysub;
    
    use subs gw(sub1 sub2);
    
    
  • Definition:
    
    sub mysub {
    
    …
    
    …
    
    }
    
    
  • Direct call techniques
    
    mysub;
    
    mysub();
    
    $result=mysub;
    
    $result=mysub();
    
    

 

Return Values

  • Through the reference mechanism, a function can modify its arguments.
  • Other way to return a value or a list of values to the caller:
    • use the return function with the subroutine: return $value;
    • rely on the last expression evaluated in the subroutine

 

Functions for Scalars or Strings

  • chop – removes last character from a scalar argument or each element of an array argument.
  • chomp – similar except only removes the $/ character(s) (e.g. new line) or each element of the argument array
    • $scalar = chomp ($myinput = <STDIN>);

      is one way to read a line of input.

  • uc, ucfirst, lc, lcfirst – change the case of strings
  • index – find a substring within a string
  • length – return the number of bytes in a string
  • reverse – flip a string or a list
  • substr – get or alter a portion of a string

Perl Arrays & Hashes Notes

Published by:

Arrays
#!/usr/local/bin/perl
@words1=("red","green","blue","white","blue","red");
@words2=qw(one two three four);
print "both words1 and words2 are simple arraysn";
foreach $aword(@words1)
{
print "The word is " . $aword ."n";
}
foreach $aword(@words2)
{
print "The word is " . $aword . "n";
}	
$words1[0]="top";
$words1[1]="side";
$words1[2]="left";
foreach $aword(@words1)
{
print "The word is " . $aword ."n";
}
# Accessing values
$var = $words1[3];
print "The value of 4th element in words1 array is: " . $var ."n";

# Length of array
$length=@words2;
print "The length of words2 array is: " . $length ."n";

 

Associative Array
#!/usr/local/bin/perl

%employees=("Fred" => "CEO", "Harry" => "General Manager", "Mark" => "Cleaner", "Sally" => "Programmer");
while(($key,$value)=each(%employees))
{
print $key.", ".$value. "n";
}

# Promote Sally to Head Programmer
$employees{"Sally"}="Head Programmer";
print "Sally now is: " .$employees{"Sally"}."n";

# Harry's position
$position=$employees{"Harry"};
print "Harry's position is: " .$position."n";

 

Subroutine
#!/usr/local/bin/perl

sub printstuff
{
print "First arg is: ".$_[0]."n";
print "Second arg is: ".$_[1]."n";
}
print "calling a subroutinen";
printstuff("one line","next line");
printstuff(5,7);

 

Question 1
#!/usr/local/bin/perl
# The first element of the array should contain the word "Zero" the second "One" the third "Two" etc up until the last element which should be "Nine". Use the foreach control statement to list all the elements of the array.

@array=("Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine");
print "Array contains: n";
foreach $listarray(@array)
{
print $listarray."n";
}

 

Question 2
#!/usr/bin/perl
#  The first element of the array should contain the word "Zero" the second "One" the third "Two" etc up until the last element which should be "Nine". The program should take one argument, an index into the array. It should return the element in the array corresponding to this index. 
%array=('Zero'=>'0','One'=>'1','Two'=>'2','Three'=>'3','Four'=>'4','Five'=>'5','Six'=>'6','Seven'=>'7','Eight'=>'8','Nine'=>'9');
print "The value is:" .$array{$ARGV[0]}."n";

 

Question 3
#!/usr/bin/perl
# Write a perl program that reads in a text file containing one word per line. Create a hash containing the words read as 
#$keys and the number of times they have been read as the value.
#Print out each word and its frequency
print $ARGV[0]."n";
open(FILE,$ARGV[0]);
while($line=<FILE>)
{
chomp($line);
if(exists($count{$line}))
{
$count{$line}++;
}
else
{
$count{$line}=1;
}
}
while(($word,$occurrences)=each(%count))
{
print $word." ".$occurrences."n";
}