Perl Examples:

     General Tasks


Perl examples of printing, variables, comments, basic string handling, if/then/else constructs, loops, and basic Perl hashes.

 

You can download (or just cut and paste) this code to a file on your computer and then run it.  If you compare the code to the results, it might help explain Perl basics.

 

Perl Code Disclaimer                                                                         Download this Code


# General Tasks in Perl
#    because an example is the easiest way

# make sure I do things right
# "strict" forces variable declarations
use strict;



# **** Basic printing, strings,  ****
#          and variables

print "General Tasks in Perl: \n\n";

# escape codes using the \ character
print "Use \\n to add newlines\n";

print "you can do math as: 1+2*5= ",1+2*5;
print "  note the operations order.\n";
print "chr(65) = ",chr(65), "\n";
print "ord(\"A\") = ",ord("A"), "\n\n";

my($x);  # declare a variable
$x=5;

# Print Using the . character
print "Using . : ".($x+1)."-".$x."=1\n";

print "Note print can span multiple lines.
 This is the second line
 and this is the third.
 (formatting is retained)\n\n";

# another way to do multiline printing
print <<'ENDOFTEXT';
        any sort
            of text typed
                here will be printed.
$x variables are not converted

ENDOFTEXT
# ENDOFTEXT has to be on line by itself

$x="testing";
my($y)=" again";
my($tmp)=$x.$y;  # joining strings
print "add \"$x\" and \"$y\"
by using the \".\" as in \$tmp=\$x.\$y
to get \"$tmp\"\n\n";

print "Case conversion using lc and uc\n";
print lc("TEST"),"\n";
print uc("TeSt"),"\n\n";

print "The index function:\n";
print " S= ";
print index("TeSt","S");
print " in TeSt\n";
print " t= ";
print index("TeSt","t");
print " in TeSt.\n\n";

my(@list)=("A" .. "Z");
$x=@list;
print @list," has $x characters.\n";
$y="";
for $a (0..$#list) {$y=$y.$list[$a];}
print "chars 5, 6, and 7 in $y are: ";
print substr($y, 5, 3), "\n";

# assignments
$x=5;       # basic assignment
$y=5+3;     # basic math
$x++;       # add one to variable
$x+=5;      # add 5 to variable
$x+=$y;     # add y to x
print "the variables are: $x, and $y\n\n";


# ******* if/then/else *******

# Condition - numbers:  < > <= >= == !=
# Condition - strings:  lt gt le ge eq ne
# Special comparison <=> or cmp
# (number/string) =-1 less,0 equal,1 more

# quick form = (test)? if-true:if-false
# Note that this form does not make a
# complete statement

$x=5;
$y=5;
$tmp= ($x==$y)? "yes" : "no";
print "is \$x the same as \$y: $tmp\n";

# this could even be shortened to:
print "is \$x equal to \$y: ";
print ($x==$y)? "yes":"no";
print "\n";

print "Note that the
(condition)? true:false syntax
just replaces part of an expression\n";

### the standard if/then/else forms

# short if/then:
#   if (condition) { do this; }

# multiline if/then:
#   if (condition) {
#       do this;
#       do this;
#       }

# multiline if/then/else
#   if (condition) {
#       do this;
#       } else {
#       do this;
#       }

if ($x==$y) {# if variables are equal
  $tmp="yes";
  } else { # else variables are not equal
      $tmp="no";
  }
print "is \$x the same as \$y: $tmp\n\n";

print "
Logicals && and, || or
 note that right side is not evaluated
 if left  side determins result this is
 why || die works. If the left side is
 true, the right side is  not evaluated.
 If it's false, then the right side is
 evaluated and the process stops.
 \n";


#***** Loops and Lists ******
@list=('item1','item2','item3','item4');
#could also do it as:
# @list = qw(item1, item2, item3, item4);

# this prints the number of elements
print "There are ".scalar @list;
print " items in the list\n";

$tmp=@list;   # this returns a count
print "The list is: @list,
it has $tmp items\n\n";

print "When working with lists, \$#list
is the index of the last item. Remember,
lists start counting from 0 (unless you
change the default)
\n";

# Notes on for:
#my $value (@array) { $value }
# for (@array) { $value = $_; }
# for my $index (0..$#array) {
#    $value = $array[$index];
# }
# for (0..$#array) {$value = $array[$_];}

# There is no difference between
#  for and foreach

foreach (@list) {
    print ".";
    }
print "\n";

foreach $x (@list) {
    print "$x, ";
    }
print "\n";

# loop through all list items
for $x (0..$#list) {
    print "$x = $list[$x], ";
    } # end of loop
print "\n";

$x="Test of the Perl substr system";
print "$x = ", length($x);
print" characters long.\n";
for $y (1 .. length($x)) {
    print substr($x, length($x)-$y, 1);
    }
print " = backwards\n\n";
# there is a perl command to reverse
# strings as well.

# you can do stuff like this too:
print "quick loop $_\n" foreach @list;

my(@arr1, @arr2);
print "the map function puts each element
of the right array through the block with
the results in the left array.\n";
@arr1 = qw(zero, one, two, three, four);
@arr2 = map{uc($_)} @arr1;
print " @arr2 ";


# Removing duplicate array items while
# preserving order

my(%seen);  # %seen is a hash
@arr1 = qw(one two one three four two);

foreach (@arr1) {
    push(@arr2, $_) unless ($seen{$_}++);
}

print "@arr2";

# note that the %seen hash is used as
# a test.  ++ eq +=1



#******** Hashes *********
# hashes are lists with strings as keys
# basic syntax is %hash, $hash{key}

my(%hash);
print "\nBuilding a Hash\n";
for $x ("a".."e") {
  $y = "data-".$x;
  print "entry keyed with $x is being ";
  print "set to value $y\n";
  $hash{$x}=$y;
}

$tmp=%hash;
($x,$y)=split(/\//,%hash);
print "the hash has $x entries\n";

print "\nPrinting Hash entries\n";
while (($x, $y)= each %hash) {
  print "hash keyed by $x is $y\n";
}

# deleting a hash entry:
delete $hash{"b"};

print "\nHash entries after delete\n";
while (($x, $y)= each %hash) {
  print "hash keyed by $x is $y\n";
}

($x,$y)=split(/\//,%hash);
print "the hash has $x entries\n";

# converting hash keys to an array
@list=(keys %hash);
print "the keys are: @list\n";

Feel like leaving

A comment?

Use the associated Blog

Here

.

.

.

.

.

.