The Cache: Technology Expert's Forum
Welcome, Guest. Please login or register. September 16, 2019, 09:19:58 PM

Login with username, password and session length

Pages: [1]
Author Topic: Fatty's Perl Top 5  (Read 2387 times)
Offline Offline

Posts: 11

View Profile
« on: May 06, 2007, 07:44:33 AM »

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.

use strict;

my $foo;  # predeclare the scalar
$fpp = "test" # $fpp undefined because you can't type properly, this won't pass perl -c

2. Learn to use the data structures properly.  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::Dumper - makes sense of fished up structures like the above

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

$ perl /tmp/
$VAR1 = {
          'bar' => [

3. Learn to use the perl debugger.  Putting prints in your code gets real old, real fast

perl -d

4. Think about your code because it's really easy to make perl code that sucks...  Devel::Profile 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 regexps (^ $) to improve efficiency.  Avoid .*, especially multiple .*'s in the same regexp because it probably won't behave the way you think it will  Smiley  .*? 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


No links in signatures please
Olde World Hacker
Offline Offline

Posts: 10096

View Profile
« Reply #1 on: May 06, 2007, 11:31:06 AM »

That's great stuff fatty - nice post

It is now believed, that after having lived in one compound with 3 wives and never leaving the house for 5 years, Bin Laden called the U.S. Navy Seals himself.
Pages: [1]
Jump to:  

Perkiset's Place Home   Best of The Cache   phpMyIDE: MySQL Stored Procedures, Functions & Triggers
Politics @ Perkiset's   Pinkhat's Perspective   
Powered by MySQL Powered by PHP Powered by SMF 1.1.2 | SMF © 2006-2007, Simple Machines LLC
Seo4Smf v0.2 © Webmaster's Talks

Valid XHTML 1.0! Valid CSS!