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
- for (my $i = 0; $i <= $#foo; $i++) { # BAD
- foreach (@foo) { # BETTER
- Don't use them where a while will do
- for (my $i = <STDIN>; $i; $i = <STDIN>) { # BAD
- 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:
- my $array = [ 'one', 'two', 'three' ];
- This is "anonymous" because we didn't have to create an array
- Hashes have a similar constructor
- 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
- qq//
- qq#A decent <html> delimiter </html> #
- 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, usemy
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