Thread: Fatty's Perl Top 5
Fatty

Top 5 things for

perl

  newbies to do/

learn

 

1. Use strict.  Always.  It forces certain proper behaviours on you and finds most common errors at compile time.


#!/usr/bin/

perl

 
use strict;

my $foo;  # predeclare the scalar
$fpp = "test" # $fpp undefined because you can't type pro

perl

 y, this won't pass

perl

  -c


2.

Learn

  to use the data structures pro

perl

 y.  Especially hashes. But especially refs


my $ref; # placeholder
$ref->{foo} = "bar";  # hashref
$ref->{foo}->[0] ="bar"; # now a hashref pointing at an arrayref


3. Data:Applauseumper - makes sense of fished up structures like the above


$ cat /tmp/test.pl
#!/usr/bin/

perl

 
use strict;
use Data:Applauseumper;
my $foo;
$foo->{bar}->[0] = "baz";
print Dumper $foo;

$

perl

  /tmp/test.pl
$VAR1 = {
          'bar' => [
                    'baz'
                  ]
        };


3.

Learn

  to use the

perl

  debugger.  Putting prints in your code gets real old, real fast

perl

  -d foo.pl

4. Think about your code because it's really easy to make

perl

  code that sucks...  Devel:Applauserofile is a good module to see which functions get called the most and how much time they take.  Avoid making the same

regex

  over and over -- save your variables or the results of expensive calculations in a structure.

$foo =~ /^(d+)/;
my $firstnumbers = $1; # whatever was in parens

($firstnumbers) = ($foo =~ /^(d+)/); # one line format, a

regex

  returns an array of ($1, $2, ...)

In the last one don't forget to put $firstnumbers in parens because it casts it to an array (in scalar context $~ returns the number of matches, not the values)

Similarly, try to anchor your

regex

 ps (^ $) to improve efficiency.  Avoid .*, especially multiple .*'s in the same

regex

 p because it probably won't behave the way you think it will  Applause  .*? is a non-greedy version, google "

perl

  backtracking" to find more

5.

Learn

  about the

perl

  one liners, especially -p/-n and -i. 

perl

  -p -i.bak -e 's/fish/fsck/g'  *.

php

 


will replace fish with fsck in all of the .

php

  files, saving the old file with a .bak extension

perkiset

That's great stuff fatty - nice post


Perkiset's Place Home   Politics @ Perkiset's