perl - Declare Array and Push in the Same Loop Statement -
declare array , push in same statement
this won't work:
push( my(@arr), '') 0..$somenum; # [] however, if use package variable, it'd give desired affect:
push( our(@arr), '') 0..$somenum; # ['','','', ...] but comes unwanted side-effects.
is there reasonable, concise, all-in-one solution? or using 2 statements best advice?
my @arr; push( @arr, '' ) 0..$somenum; # ['','','', ...] i want avoid multiple statements. when there many arrays being populated looks cluttered , there wasted space.
i realize above can done without push (i.e., my @arr = ('') x $somenum;), different reasons, wanted use push. @texasbruce made point map better this, though there debates using map purpose. still, @ fun exercise.
my ... ... officially undefined behaviour.
note: behaviour of
my,state, orourmodified statement modifier conditional or loop construct (for example,my $x if ...) undefined. value ofmyvariable mayundef, assigned value, or possibly else. don't rely on it. future versions of perl might different version of perl try out on. here dragons.
(emphasis in original.)
to assign values new array, use assignment.
my @arr = ('') x ($somenum+1); if values assign vary, use map.
my @arr = map { 2*$_ } 0..$somenum;
Comments
Post a Comment