Tuesday, March 23, 2010

New Perl Hate

You don't work with a language every day without building up a "things I hate in language X" list. Well, I have a few hates of Perl, but they've all been fairly well covered in other blogs and cover the usual topics (pre-Moose OO, getting bitten by scalar/list context, etc), however yesterday I came across a new one. Here is a one-liner demonstrating the problem:

$ perl -MData::Dumper -le'@a=qw/a b c/; @foobar = map { $_ } @a[0..7]; print Dumper \@a'
$VAR1 = [
          'a',
          'b',
          'c',
          undef,
          undef,
          undef,
          undef,
          undef
        ];

Fairly obviously, I have created a list with 3 elements in it, tried to slice it with 8 values and assign that to a different list, however when printing the contents of the original list, it has now been padded out to 8 values with undefs. Ok, I thought perhaps doing a slice on a list had that kind of destructive behavior but I had just never noticed it before and had never heard about it previously. So I tried another one-liner to perhaps prove that theory:

$ perl -MData::Dumper -le'@a=qw/a b c/; @foobar = @a[0..7]; print Dumper \@a'
$VAR1 = [
          'a',
          'b',
          'c'
        ];

Nope. Bug? Or expected behavior for some reason that I cannot figure out? This was on Perl 5.8.9

1 comment:

  1. Not sure if it's a bug per-se, but it does make some sense - look at this code, for example:

    perl -MData::Dumper -le'@a=qw/a b c/; $_ for @a[0..7]; print Dumper \@a'

    It exhibits the same behavior as using map. I'm guessing that, while an array slice does not auto-vivify non-existent elements, the iteration over those non-existent elements as done in a loop does.

    Of course, that's just a guess, but if I knew how to read the output from -MO=Concise I could probably say for sure.

    ReplyDelete