in reply to [Solved] Avoiding repeated undefs

Hello davies,

> It seems to me to be inelegant to repeat undef

No, is not. Compiler does not bother with elegance ;)

Anyway I suspect you cannot avoid them repeated: you are are in left side of an assignement, and inside a my declaration: no array (well you mean list?) can be there.

PS

An eventual list as second (or whatever..) element in the assignement will slurp everything

perl -e "$str = 'a b c d e f g';@arr=(1,2,3,4,5); ($key, @arr, $val) = + split(/\s+/, $str); print qq($key $val\n@arr\n)" a b c d e f g # even if the array is presized: perl -e "$str = 'a b c d e f g';$#arr=4; ($key, @arr, $val) = split(/\ +s+/, $str); print qq($key $val\n@arr\n)" a b c d e f g

L*

There are no rules, there are no thumbs..
Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.

Replies are listed 'Best First'.
Re^2: Avoiding repeated undefs
by hippo (Archbishop) on Feb 26, 2019 at 10:08 UTC
    even if the array is presized

    If you specify the slice in the assignment it's fine though:

    use strict; use warnings; use Test::More tests => 1; $_ = "Anyway I suspect you cannot avoid them repeated: you are are in +left side"; my @undef; my ($key, $val); ($key, @undef[0..4], $val) = split(/\s+/, $_); is ($val, 'them');

    I still prefer Eily's approach, however.

      Similar approach:
      ( my $key, (undef) x 5, my $val) = split(/\s+/, $_);
      Note: 'undef' must be enclosed with parentheses to force list context for 'x' operator.