map typically returns the number of elements that are in your original list. How does map return fewer elements? --By using a test and upon failure return an empty list, "()" because undef, 0 (zero), or leaving off the empty list all create extra elements in the list.
I recently had a need to splice an array into 4 element array refs. Here's an example implementation:
# use CGI because it has subs that operate on array refs
use CGI qw/:standard/;
use Data::Dumper;
use strict;
my @list = (1..7);
print "list: ", Dumper(\@list),"\n";
# set the number of elements for the splices
my $num_elements = 4;
my @newlist =
# This map operates on the list of splices.
# If you remove the empty list "()" extra
# empty elements will appear in your new list.
#
# CGI::Tr( $array_ref ) is used for demonstration purposes.
map { Tr($_) }
# This map operates on the spliced elements.
#
# CGI::td( $array_ref ) is used for demonstration purposes.
map { td( [ splice(@list,0,$num_elements) ] ) }
0 .. (@list/$num_elements);
print "newlist: ", Dumper(\@newlist),"\n";
__END__
>perl example.pl
list: $VAR1 = [
1,
2,
3,
4,
5,
6,
7
];
newlist: $VAR1 = [
'<tr><td>1</td> <td>2</td> <td>3</td> <td>4</td></tr>',
'<tr><td>5</td> <td>6</td> <td>7</td></tr>'
];
Update: Changed the list from @_ to 0 .. (@_ / $num_elements) and removed some extra error checking from the top map. Thank you Aristotle for your suggestions.
$num_elements = 4; @_ = ( list,of,elements,to,splice ); @spliced_list = # This map operates on the list of splices. # the left side of || should test something # most likely something in $_ and return # something (or call a sub) if the test is # successful, and if the test fails, it should # failover to the right side of the || which # returns (). map { func1($_) } # This map operates on the spliced elements. # Splicing the list removes those elements # from the list as a side affect. map { func2( [ splice(@_, 0, $num_elements) ] ) } # Since this snippet shows how to fold an array, # we only need to iterate over the count of # new elements. 0 .. (@_ / $num_elements);
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Fold a list using map splices
by Aristotle (Chancellor) on Feb 19, 2003 at 22:59 UTC | |
by hiseldl (Priest) on Feb 20, 2003 at 15:25 UTC | |
by Aristotle (Chancellor) on Feb 20, 2003 at 17:54 UTC | |
by hiseldl (Priest) on Feb 20, 2003 at 21:28 UTC | |
|
Re: Fold a list using map splices
by BrowserUk (Patriarch) on Feb 21, 2003 at 17:00 UTC | |
by Aristotle (Chancellor) on Feb 22, 2003 at 00:03 UTC | |
by BrowserUk (Patriarch) on Feb 22, 2003 at 06:31 UTC | |
by Aristotle (Chancellor) on Feb 22, 2003 at 15:24 UTC | |
by hypochrismutreefuzz (Scribe) on Sep 04, 2004 at 01:38 UTC | |
| |
by BrowserUk (Patriarch) on Feb 22, 2003 at 21:09 UTC |