Constructs

C-style loops are usually unnecessary

  • You can do C-style for loops,but you often don't need them
  • Don't use them where a foreach will do
  1. for (my $i = 0; $i <= $#foo; $i++) { # BAD
  2.  
  3. foreach (@foo) { # BETTER
  • Don't use them where a while will do
  1. for (my $i = <STDIN>; $i; $i = <STDIN>) { # BAD
  2.  
  3. while (my $i = <STDIN>) { # BETTER
  • Think about what you're coding and do what makes sense

Anonymous hashes & arrays

  • Create an anonymous array reference, and assign it:
  1. my $array = [ 'one', 'two', 'three' ];
  • This is "anonymous" because we didn't have to create an array
  • Hashes have a similar constructor
  1. my $hash = { one => 1, two => 2, three => 3 };
  • Treat as you'd otherwise treat a reference

q[qrwx]?//, m//, s/// and y///

  • Perl lets you specify your own delimiters for:

    • Single quotes: 'text' => q/text/
    • Double quotes: "text" => qq/text/
    • Regular expressions: qr/text/
      There is no other way to specify a regular expression match like this in Perl outside of a match or substitution operation.

    • Words: ("text", "text") => qw(text text);

    • Backticks: text => qx/text/
    • Regex match (m//), Regex substitute (s///), and translate (tr///, y///) work the same way
  • You can use any character except whitespace.
  • But use something balanced like parens or braces
  1. qq//
  2. qq#A decent <html> delimiter </html> #
  3. qq( man perl(1) for details ) # valid!

global, local, my, our

  • Declare global variables with use vars.
  • Declare lexical variables with my
  • local is not what you think, use my instead unless you know why you're using local
  • Use our only when your package needs a global variable

Want to contribute?

Submit a PR to github.com/petdance/perl101