One page on Perl
by H. Roumani


Differences from Java


File I/O

To open a file:
  open(FILEHANDLE, filename) or die "Could not open $!";
The open mode prefixes the filename:

open(FILEHANDLE, <filename)opens the file for reading
open(FILEHANDLE, >filename)opens the file for writing
open(FILEHANDLE, >>filename)opens the file for appending

Once the file is open, you can read its lines into an array in one shot, process it line by line, or treat it as binary and process it byte by byte.

To read the entire file into an array @a, use @a = <FILEHANDLE>; (this parses the file's content into array elements based on $/, which is \n by default). Similarly, to write an array @a into a file, use print @a; (this uses $\ as record delimiter, which is "" by default so make sure each element has \n if you want an element per record).

To synchronize multiple simultaneous accesses to a file, use a second file as a semaphore.
  use Fcntl qw(:flock);
  ...
  open(LOCK, ">write.lock")
  flock(LOCK, LOCK_EX);
  # now open your file and process it
  close LOCK;
  # close your file;

Pattern Matching

Use:

if ($entry =~ m/regex/i)
to see if $entry matches the specified regular expression. The i suffix implies "ignore case" as in grep. You can also do substitution and translation the same way as shown in the following two examples:
$a =~ s/the/The/g; # replace "the" with "The" globally
$a =~ tr/\r//;     # replace ^M with nothing throughout
And to extract the matching substring, surround the sub-regex with parentheses and look at $1. For example, to extract the age from a string $s that contains "age=22;", use:
if ($s =~ m/.*age=(\d+);.*/) { print $1; }