Grouping perl foreach values
Alex Satrapa
grail at goldweb.com.au
Tue Jul 9 15:15:54 EST 2002
On Tuesday, July 9, 2002, at 11:09 , Michael Still wrote:
> I have a list of value in the form:
>
> v1;v2;v3;v4;v5;v6;v7;v8;v9
>
> And I want to work through them in sets of three, something like:
>
> foreach($cola, $colb, $colc) ($listofthings){
> ... do stuff ...
> }
What's important about the groups of three?
Perhaps if there's some data structure there, you should implement it as
a structure in Perl, and use foreach to iterate over a list of these
structures?
Otherwise, you don't really want to use foreach anyway, you might have
luck with something like:
for ($i=0; $i < (scalar(@list)/3); $i++) {
@sublist = @list[$i * 3 .. $i * 3 + 2];
# Do stuff with three elements in sublist here
}
But this is probably the wrong tool for the wrong job. Slightly less
wrong might be:
while (scalar(@list)) {
$foo = shift @list;
$bar = shift @list;
$baz = shift @list;
# Do stuff with foo/bar/baz here
}
Though that does assume that your list has (n * 3) items in it, and
you're going to have trouble if it doesn't.
Get the data structure right, and the code will be self-evident.
Alex
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 225 bytes
Desc: not available
Url : http://lists.samba.org/archive/linux/attachments/20020709/cced5eed/attachment.bin
More information about the linux
mailing list