$
, arrays of scalars prefixed by @
, or
hashes of scalar pairs (similar to Java's maps) prefixed by %
.eq
, gt
, lt
, etc. for string comparisons.foreach
for hashes.param
and %ENV
.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
(this uses
$\
as record delimiter, which is ""
by default so make
sure each element has \n
if you want an element per record).
use Fcntl qw(:flock); ... open(LOCK, ">write.lock") flock(LOCK, LOCK_EX); # now open your file and process it close LOCK; # close your file;
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 throughoutAnd 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; }