in reply to bit of help with map function
This bit is quite wrong:
my @names = map {$i > 6 ? push(@names,$input2arr[$i]) : $i++ } @input2 +arr;
Inside the map block (i.e. the bit between { and }) you don't just put the equivalent of what you'd put inside a foreach block. Allow me to demonstrate with a simple example...
my @letters = ('a', 'b', 'c'); my @capitals; foreach my $l (@letters) { push @capitals, uc($l); }
Don't do this:
my @letters = ('a', 'b', 'c'); my @capitals = map { $i++; push @capitals, uc($letters[$i]) } @letters +;
Do this:
my @letters = ('a', 'b', 'c'); my @capitals = map { uc($_) } @letters;
What map does basically is to execute the contents of the block on each item in the given list, making a new list from all the results. Note in the above example, the code within the block doesn't need to do any pushing onto @capitals, and it doesn't need to look at @letters - the map function does that for you.
Your particular example can be written as:
my $i = 0; my @names = map { $i++ > 6 ? ($_) : () } @input2arr;
Though using grep in this case might be better.
my $i = 0; my @names = grep { $i++ > 6 } @input2arr;
Or just use an array slice:
my @names = @input2arr[ 7 .. $#input2arr ];
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: bit of help with map function
by sweepy838 (Acolyte) on Apr 30, 2012 at 22:06 UTC |