Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Some great web pages to learn about Perl

Please comment if you know some more good ones.

Perl Basics

Perl Data Types

  • Scalar -> $variable
  • Array -> @array
  • Associative Array (hash) -> %hash
  • Combinations to make complex types easily (looks confusing but very powerful)
  • Array of hashes $array[$i]->{$key}
  • Hash of hashes $hash{$key}{$var}
  • Multi-dimensional $var->{$key}->[0]->{$thing}

Use it!

Code Block
use strict;

Perl if statement

 

Code Block
themeEmacs
use strict;
my $string = "this is a string";
if ( $string eq "string" ) {
  print "$string is the same as \"string\"\n";
}
elsif ( $string =~ /string/ ) {
  print "regex match $string has \"string\" in it\n";
}
elsif ( $string == 100 ) {
  print "$string is the number 100\n";
}
else {
  print "Else Nothing\n";
}

Perl Loops -> While

Code Block
while (condition) {
  # do something
}

Perl Loops -> for

Code Block
use strict;
my @array = (1, 2, 3, 4, 5, 6);
for ( my $i = 0; $i <= $#array; ++$i ) {
  print “i=$array[$i]\n”;
}

Perl Loops -> foreach

Code Block
use strict;
my @array = (1, 2, 3, 4, 5, 6);
foreach my $i ( @array ) {
  print “i=$i\n”;
}

Open a file and loop through

Code Block
use strict;
my $match = "blah";
my $file = "textfile.txt";
my $lines = 0;
open (DATA, $file) or die "ERROR with $file. $!";
while (<DATA>) {
  chomp; # not necessary but gets rid of trailing spaces and newlines.
  if ( $_ =~ /$match/) {
    print "$lines: $_\n"; 
  }
  ++$lines;
}