Quirky Perl tricks

2661229044_fb203928cc_oPerl is like a sharp knife: you can do a lot of things with it easily (like carve wood), but you easily hurt yourself. So here are some quirky things which I discovered (credit goes to my friends who came to me with these issues and helped me to grow my knowledge by researching the issues).

  • First issue: what is wrong with the following code? (in fact there is nothing wrong, but it can behave in unexpected ways):
my ($input) = <STDIN>;
print "Got: $input";

The unexpected behavior is that this code tries to read multiple lines, instead of a single line. The explanation is hat Perl subroutines know if they are expected to return a single value or an array of values, and in this case it concludes that you want an array, which means all the lines from the file handle (the standard input in this case). However Perl doesn’t have any way (as far as I know :-)) to find out exactly how many elements you want, so it has to give you all and throw away the superfluous elements at the assignment. What is the solution? Either omit the parenthesis around the variable declaration (which implicitly tells Perl that you need a scalar) or explicitly evaluate the read operator in a scalar context. The example below shows both methods (although either one is sufficient):

my $input = scalar(<STDIN>);
print "Got: $input";
  • Second issue: is it possible to extract more than one value from a for cycle during one iteration? The code would be something like this:
foreach my($foo, $bar) (qw/a b c d/) {
	print "$foo, $barn";

From what I know, this is currently not possible, although there is a proposal for this in Perl6.

Picture taken from kaibara87’s photostream with permission.


Leave a Reply

Your email address will not be published. Required fields are marked *