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