Perl Tips

anim-bulbglow.gif (80393 bytes)

Acacia is happy to provide programming tips. Help others by adding your own tips to this page.


The tips shown here are for information only and should be tested thoroughly before use in any production environment.

Last updated 18:07:39-20/12/2008

Click here to add your own tips.

Click to search the Acacia site
Click to search using Google

Perl Tips

Practical Extraction and Reporting Language.

Tip Details
Adding pipeline
Geoff
#!/usr/bin/perl
$total = 0;
while(<stdin>)
{
$val = $_ + 0;
$total += $val;
}
print "Total = $total
";
(@array) = split(/:/, $string);
Acacia
This will split $string into an array of items by chopping the string at each colon (:).  Individual elements can be access using $array[0] etc.
File Processing
Acacia
if ($var =~ /^[abc]*[def]$/) print "Found";
Details: This line will print the word "Found" if $var contains any string that starts with a, b or c and ends with d, e or f.  This type of regular expression processing is a key reason to use perl on your next project.
Grab web site via perl
Geoff
#!/usr/bin/perl

# Create a user agent object
use LWP::UserAgent;
$ua = new LWP::UserAgent;
$ua->agent("AgentName/0.1 " . $ua->agent);

# Create a request
my $req = new HTTP::Request GET => 'http://xena/';
$req->content_type('application/x-www-form-urlencoded');

#
Pass request to the user agent and get a response back
my $res = $ua->request($req);

# Check the outcome of the response
#if ($res->is_success) {
print $res->content;
#} else {
# print "Bad luck this time
";
#}
Looping through hashes
Geoff
foreach $word (keys %wordlist)
{
print "$word was seen $wordlist{$word} times
";
}
Perl In-Line C
Geoff
use Inline C => <<'END';
#include <stdio.h>

int my_rename(char *from, char *to)
{
return rename(from, to) >= 0;
/* -1 bad 0 good */
}
END

my_rename("fred","barney") or die "couldn't rename
";
Perl Module Layout
Geoff
Inside your PM perl module (use perldoc mm.pm):

#!/usr/local/bin/perl
# Name this package
package mm;

# Start of perldoc
=head1 SYNOPSIS
....synopsis...
=cut
# End of perldoc
....your module subroutines...
1;

Reading files
Acacia
open(INFILE, "<filename.txt") or die "Unable to open file";
while(<INFILE>)
{
chop($_);
$line = $_;
print "Line is [$line]";
}
Regular expression replacement
Acacia
$line = <stdin>; # read a line from the console
($num, $street) = $line =~ /([0-9\.]+) ([a-zA-Z]+)/;
(@chars) = split(//, $line); # @chars[1] is the 2nd character.
Signal handling
Geoff
$TIMEOUT=180; # seconds

# Declare Trap signal handlers
sub INT_handler
{
print "Process received INT signal
";
exit 1;
}
sub ALARM_handler
{
print "Process aborted after $TIMEOUT sec timeout
";
exit 1;
}

# Initialise signal handlers
$SIG{'INT'} = 'INT_handler';
$SIG{'ALRM'} = 'ALARM_handler';

# allow process to run for $TIMEOUT sec before exiting (suicide)
alarm($TIMEOUT);

....... code to do processing ...

Click here to add your own tips.