The Source_er’s Apprentice:Powerful Tips & Techniques in Perl you can start using today
Matthew Heusserxndev.com - [email protected] to the West Michigan Perl Mongrels – 8/25/2006
Techniques
… there is a distinct difference between learning to use Perl, and learning to use it well. In my opinion, the best way to learn any language well is to see how others have used it to solve problems
- Some Dude on Amazon.com
Velocity & Pinball skills
Trick #1:Use Parameters
my $new = convert('616-555-1212');print "New Number is $new\n";
sub convert { my $num = shift; $num=~s/^616-5/269-5/g; $num=~s/^616-31/269-31/g; $num=~s/^616-32/269-32/g; return $num;}_
Trick #2:Use Interpolation
my $cash = 50;
my $one = 'The $cash variable is $' . $cash;
my $two = "The \$cash variable is \$$cash";
print $one . "\n";
print "$two \n";
Trick #3:use strict
$str = "Hello, World\n";
print "The value in str is $Str";– BAD!
use strict;my $str = "Hello, World\n";print "The value in str is $Str";
- GOOD!
Trick #4:Become a scope master
use strict;
{
my $name = "joe";
}
print $name;
Trick #5: File Handles
my $f = open_file("TRICK1.TXT");while (<$f>) { print $_;}
sub open_file { my $file = shift; open INFILE, $file
|| die "Could not open $f for read"; return(\*INFILE);}
Trick #6: use croakuse Carp;my $f = open_file("TRICK2.TXT");while (<$f>) { print $_;}
sub open_file { my $file = shift; open INFILE, $file or croak "Could not open $file for read"; return(\*INFILE);}
Trick #7: Handle Exceptions with eval
use Carp;
eval(run());
if ($@) {
print "Died with message $@\n";
}
sub run {
croak "ribbet. ribbet.\n";
}
Trick #8:Use Warnings
use warnings;
my $val;
$val = $val+5;
# or ($val = val + 5);
print "val is $val\n";
Trick #9 To create an error log, re-direct STDERR
trick8.pl 2>err.txt
Trick #10:ArrayRefs as output
my $rasquares = get_squares(16);print "The square of 8 is $rasquares->[8]\n";
sub get_squares { my $num = shift; my @arr; if ($num<1) { croak "get_squares must be a number"; } for (my $idx=0; $idx<$num; $idx++) { $arr[$idx]=$idx*$idx; } return \@arr;}
Trick #11:Avoid C-Style for loops … use foreach
my $rasquares = get_squares(16); my $idx; foreach my $val (@$rasquares) { print "$val\n"; }
sub get_squares { my $num = shift; my @arr; if ($num<1) { croak "get_squares must be a number"; } for (my $idx=0; $idx<$num; $idx++) { $arr[$idx]=$idx*$idx; } return \@arr;}
Trick #12:Use ‘Named Parameters’
my %params = ('height',10,'length',5,'width',3);print volume(%params);
sub volume { my %param = @_; return $param{'height'}*$param{'width'}*$param{'length'}; }
Trick #13:Direct-Attack your RegExps
sub convert { my $num = shift; $num=~s/^616-5/269-5/g; $num=~s/^616-31/269-31/g; $num=~s/^616-32/269-32/g; return $num;}
Trick #14:Use Regular Expression Memory
my %switches;open INFILE, "trick12.txt" or croak "failed to open trick12.txt for read";
while(my $str = <INFILE>) { $str=~ /^\d\d\d-(\d\d\d)-\d\d\d\d/; my $switch = $1; if (!defined($switches{$switch})) { $switches{$switch} = 0; } $switches{$switch}++; print "$switch\n"; }
Trick #15:Create lists of lists with referencesmy $tictac;
my ($idx, $jdx);for ($idx=0; $idx<3; $idx++) { for ($jdx=0; $jdx<3;$jdx++) { $tictac->[$idx]->[$jdx] = "-";
}}
Trick #16:Read a file into an array
chomp(my @data = <INFILE>);
Trick #17:Turn off Warnings when you want
use warnings;my @arr;$arr[0] = 'Some';$arr[1] = 'Values';$arr[3] = 'And some whitespace';$arr[5] = 'To be Concatenated';my $str = join(',', @arr);print $str . "\n";
{ no warnings; my $str = join(',', @arr); print $str . "\n";}
Trick #18:use backticks
my $str = `ls -l`;my @arr = split(/\n/, $str);my $file = $arr[0];$file=~/[-rwxa][-rwxa][-rwxa][-rwxa]\s*(\d*)\s/;my $size = $1;
$file=~/\s200\d\s\s([\w\W]*)/;my $name = $1;print "$name has a size of $size";
Trick #19:‘Sniff’ files with –e and -s
• Or –x, -o, -d, -T,-B, -M …
if (-e 'trick19.pl') {
my $size = -s 'trick19.pl';
print "The size of trick19.pl is $size \n";
}
Trick #20:Avoid manipulating @_ …
… Unless you really want to.
my $total = 6;double($total);print "Total is $total\n";
sub double { $_[0]*=2;}
Trick #21:Named parameters via anonymous hashrefs
print volume({height=>10, length=>5, width=>3});
sub volume { my $rparam = shift; return $rparam->{'height'} *$rparam->{'width'} *$rparam->{'length'}; }
Trick #22:Make your subs type-safe
sub volume { my $rparam = shift; if (!defined($rparam) || ref($rparam) ne 'HASH') { croak('volume function expects a hashref'); } return $rparam->{'height'} *$rparam->{'width'} *$rparam->{'length'}; }
Trick #23 - Decode
• $foo = $str ? 'Y' : 'N';
Trick #24Pull off parameters
• $isTest = $parameters =~ s/^(TEST)//;
Trick #26Use map
@doubled = map { $_*=2} @single;
# Doubles the numerical
#value of a list
Trick #27Use grep
$matches = grep /\$/, @costs;
@us_dollars = grep /\$/, @costs;
Trick #28Learn to use pop, push, shift, unshift# AN ARRAY @coins = ("Quarter", "Dime", "Nickel");
# ADD ELEMENTS push(@coins, "Penny"); print "@coins""; unshift(@coins, "Dollar"); print "@coins"; # REMOVE ELEMENTS pop(@coins); print "@coins";shift(@coins);
Trick #29:Use a tight-feedback-loop environment
• putty / vim
What to do tomorrow
• Go to xndev.com
• Get this powerpoint
• Print it … read it … apply it
What to do next week
• Buy a book
• Experiment with new techniques
What to do next year
• Give a lightning talk
• Speak at PM’s?
• Attend a conference – YAPC::NA is cheap
Bonus: What are your favs?
• Discuss the favorite tips & techniques of the audience.