Dual-license your content for inclusion in The Perl 5 Wiki using this HOWTO, or join us for a chat on irc.freenode.net#PerlNet.
Beginners/Idiomatic Perl
From PerlNet
Perl allows a great many short cuts that are used regularly by its programmers. Some of these are detailed below.
Contents |
Short-circuiting operators
The conditional "or" operators (|| and or) can be used to short-circuit an expression. If the left-hand side of the expression returns true, the right-hand side will not be evaluated. Thus we can write:
open(INPUT, "<", "myfile.txt") or die "File could not be opened";
open(INPUT, "<", "myfile.txt") || die "File could not be opened";
If the file cannot be opened for whatever reason the expression on the right-hand side will be evalated and Perl will die with an error.
The conditional "and" operators can also be used similarly as follows:
($a == 5) && print "a is 5";
$a == 5 and warn "a is 5"
however these are generally better written with if statements:
print "a is 5" if $a == 5;
if($a == 5) {
print "a is 5";
}
Default values
The same short-circuiting properties described above can be used to assign default values:
my $b = $a || 5;
my $param = shift || "default_value";
In this case, the left-hand side of the expression is tested for truth, and if it's false, the value on the right-hand side is assigned (even if it is also false). You'll also see this used to ensure that a variable has a defined value:
$a = $a || 0;
# also written as:
$a ||= 0;
Chaining comparisons
The || operator can be used to chain comparison operators such as cmp and <=>. In these cases if the current comparison returns equality, the later comparisons will be compared.
my @sorted_persons =
sort
{
($a->{last_name} cmp $b->{last_name}) ||
($a->{first_name} cmp $b->{first_name})
}
@persons;
map
The map function can be used to map one array into another. Each element can be converted to multiple elements if necessary.
my @mapped_filenames = map { $_.".old" } @filenames;
grep
grep in scalar context can be used to determine if an array contains a value, or has a value that matches a certain criterion:
if (grep { $_ eq $value } @array)
{
# Do something
}
# Do something if one of the elements of the array is active.
if (grep { is_active($_) } @array)
{
.
.
.
}
local
local can be used to temporarily set the value of a variable until the end of the declared scope. It can also be used with most built-in variables, with the subscripts of arrays or hashes, and with typeglobs.
my $content;
{
# Temporarily undef $/
local $/;
# Read the entire file into $content
open my $fh, "<", "hello";
$content = <$fh>;
close($fh);
}
# Now $/'s value is restored again.
{
local $hash{"hello"} = "yellow";
myfunc(\%hash); # Now myfunc will think that $hash{"hello"} is "yellow".
}
Slicing
A hash or an array can be subscripted (sliced) using another array or list.
my @a = @array[3,4,5]; # using a list
my @a = @array[@b]; # using an array
my @a = @hash{@b};

