see also: RegularExpressions for more specifics on Perl regular expressions

How to recursively get all files starting in a directory

How to do file uploading via perl

see http://www.webmasterbase.com/article/474

Perl Switches

-w use warnings
-e the next arg is the script to run (e.g perl -e 'print "hello world\n"' )
-p walks through the file argument (?) see 'global file substitution' example

Doing a global file substitution (example: perl -p -i -e 's/from/to/g' filename)

Writing to a file

# the '>' indicates I want to write to the file
open(theFile, ">dump.txt")  || die "can't open the file"; 
print theFile "I've written to the file!\n";
close(theFile);

Reading from a file line by line

Note the <> construct when blank meant from stdin. Now, it means from the open file handle.
open(theDict, "/usr/share/dict/linux.words") || die "Can't open dict\n";

while (<theDict>) {
        print;
}
close(theDict);

Reading from stdin

Examples to read in each line and print it out, pre-pended with a -*
while ($line = <>) { print "-*$line"; } basic example, but we can be more succint
...or simpler: while (<>) { $_ =~ s!^!-*!; print $_; } works because $_ means 'current line read from <>
...or simpler still: while (<>) { s!^!-*;!; print; } works beacuse $_ is assumed in the print and the substitution

Checking if a variable is defined


# '$/' is the Optional 'chunk mode' parameter.  Designates what the <> operator
#  looks for to terminate each read operation.  Default is '\n' (??)
$/ = "\n";

while (1) {
        if (not defined($junk)) {
                print "not defined\n";
                $junk = "junk";
        } else {
                print "now it's defined\n";
                last
        }
}

-- MattWalsh - 15 Aug 2002

Topic revision: r1 - 13 Mar 2006 - MattWalsh
 
This site is powered by the TWiki collaboration platformCopyright © 2008-2012 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback