A Practical Perl Guide
From Gentoo Linux Wiki
Contents |
[edit] What is this?
- an illustrated guide on Perl's capabilities, caveats, and unexpected behavior. If you hate to read documentation then this guide is for you.
- not a reference
- not a complete guide
- not too suitable for non-programmers
[edit] What is Perl good for?
Mainly: system administration tasks like parsing files etc. IMHO (and in many others' opinions) it fills the gap between tasks that can be done on the command line by some shell interpreter like BASH and tasks that require to create whole applications. Of course, you can pretty well use Perl for larger projects, but you'll also need to actually master Perl for that purpose pretty well.
Want a Perl script example? See here.
[edit] General Notes
- does not work. Use
'if (...) cmd;'instead. The same applies to loops.'if (...) {cmd;}' - Functions either return scalars or lists. They cannot return hashes. Instead return the reference to a hash: “return \%hash;”. The hash entries can then be directly accessed via “some_func()->{$key}”.
- For doing crazy things like storing hashes in arrays look at “man perldsc”.
- A complete perl documentation is available via 'man perl'.
- IMHO the most important perl documentation parts are
perlfunc code>, the perl function reference, andperlop code>, both accessible from within any shell via the 'man' command.
-
[edit] Local Variables
| Code: local variables |
[edit] Using and Defining Functions
| Code: functions |
[edit] Using Arrays
| Code: using arrays |
@some_array = (); # assign array with zero entries # append '$some_value' to the array push @some_array, $some_value; # remove last element of array and store it in '$some_value' $some_value = pop @array; # print all array elements one by one for ( $i = 0; $i <= $#some_array; $i++ ) { print $some_array[$i]."\n"; } # or foreach (@some_array) { print }; # or even.. for my $i (0..$#some_array) { print $some_array[$i]."\n";} # print all -- the easy way print join("\n", @some_array)."\n"; # create an array of words @array = ("one", "two", "three"); @array = split(" ", "one two three"); # alternative solution ($one,$two,$three) = split(" ", "one two three"); my ($one,$two,$three) = split(" ", "one two three"); # same as 'my $one;...' |
- '$#some_array' denotes the index of the last element
- '@array' is the reference to the array. Try to print it!
- Access to the array's elements is done via '$array[$integer]'. Note the difference in the usage of '$' and '@'!
[edit] Using Hashes
One of Perl's greatest features (IMHO) is the easy access to hash tables, thereby allowing a programmer to implement quite fast processing routines in nearly no time!
| Code: using hashes |
undef %hash; # 'initialize' hash (make sure it is empty) $hash{$key} = $data; # store '$data' so we may access it later by its '$key' # 'keys %hash' gives you an array of all keys # print a comma-separated list of all keys in the hash: print join(",", keys %hash); # loop over all keys existing in the hash: foreach $key (keys %hash) { print $key."\n"; } |
If your keys are not unique, then you'll have to decide on how to construct buckets. In the following example '$data' is assumed to be a text string whose values we will separate within a bucket by using a comma:
| Code: using hashes |
[edit] Operating on Files
[edit] Reading
| Code: read a text file line by line |
Let us enclose the file operation in a recursively called structure:
| Code: read a text file line by line |
That will mess up things considerably because recursively called instances will use the same file descriptor 'FILE'. A correct solution would be:
| Code: read a text file line by line |
[edit] Reading Program Output (Pipes)
There are a number of ways to read the output of a program. The most simplest being:
my $prog_output = `dmesg`; print $prog_output;
For larger programs, or those that may continuously output, or for cases where you just really want a file handle you can use:
my $program='iostat -c 2'; open(PROG, '|-', $program); while(<PROG>) { next unless /^\s+\d+/; print ; } close PROG;
[edit] Giving a program input (Pipes)
If you need to pass data to an external program, you can do so via filehandles similar to the above example, the main difference is you open them with a '-|':
my $program='/path/to/program'; open(PROG, '-|', $program); print PROG "Some data you wish the program to have\n"; close PROG;
[edit] Writing to Files
open (FILE, '>', filename); print FILE "some text\n"; # no comma! ... close FILE;
[edit] Reading Directories
The quick and dirty way is to use globs. This is best explained with an example:
foreach (</usr/bin/*>) { next if ( -d $_ || -x $_); # skip directories and executables print "$_ isn't executable.\n"; }
If you need or want to open a directory as a filehandle, use opendir:
