Perl one liners: Part I
Sometimes Perl can be used in mysterious ways yet provides powerful facility to simplify code and
at the same time to improve its efficiency.
1. For example, the following code computes the current hour and minute of local time:
my @time = localtime(time);
my ($hour, $minute) = @time[2, 1];
To achive one liner, we can use the trick of Perl array copy construct. Array is copied by dereference the reference of original array:
my ($hour, $minute) = @{[localtime(time)]}[2, 1];
In both examples, a temporary array is created.
It's possible to avoid creating temporary array, but only one scalar variable can be retrieved:
my $hour = [localtime(time)]->[2];
2. Printing a 2 dimensional array
my @ar = ([1,2], [3,4], [5, 6]);
map { print join (', ', @$_); print "\n"; } @ar;
map is a particular powerful facility in Perl language. Beginners of Perl often found map code hard to understand and use. Do not be afraid. The essen of map is simply applying a code block or expression to every element of a list (usually an array or keys/values of a hash).
at the same time to improve its efficiency.
1. For example, the following code computes the current hour and minute of local time:
my @time = localtime(time);
my ($hour, $minute) = @time[2, 1];
To achive one liner, we can use the trick of Perl array copy construct. Array is copied by dereference the reference of original array:
my ($hour, $minute) = @{[localtime(time)]}[2, 1];
In both examples, a temporary array is created.
It's possible to avoid creating temporary array, but only one scalar variable can be retrieved:
my $hour = [localtime(time)]->[2];
2. Printing a 2 dimensional array
my @ar = ([1,2], [3,4], [5, 6]);
map { print join (', ', @$_); print "\n"; } @ar;
map is a particular powerful facility in Perl language. Beginners of Perl often found map code hard to understand and use. Do not be afraid. The essen of map is simply applying a code block or expression to every element of a list (usually an array or keys/values of a hash).
<< Home