Perl Tips
Practical Extraction and Reporting Language.
| Tip | Details |
| (@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. |
| Adding pipeline Geoff |
#!/usr/bin/perl $total = 0; while(<stdin>) { $val = $_ + 0; $total += $val; } print "Total = $total "; |
| dota |
[*map/map_all_ag2.txt |
| dota |
[*map/map_all_coml10.txt |
| 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.