Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: how to print two array with new line at end of each second array element, using a single print statement?

by eyepopslikeamosquito (Canon)
on Apr 21, 2012 at 06:32 UTC ( #966313=note: print w/ replies, xml ) Need Help??


in reply to how to print two array with new line at end of each second array element, using a single print statement?

Here's a simple way:

my @nums = (1, 2, 4, 5, 8, 9); my @dat = (3, 9, 14, 10, 12, 8); for my $i ( 0 .. $#nums ) { print "$nums[$i] $dat[$i]\n"; }
Here's an alternative way using the List::MoreUtils CPAN module:
use List::MoreUtils qw(zip natatime); my @nums = (1, 2, 4, 5, 8, 9); my @dat = (3, 9, 14, 10, 12, 8); my $it = natatime( 2, zip(@nums, @dat) ); while ( my @vals = $it->() ) { print "@vals\n"; }
Update: Simpler solution using the pairwise function:
use List::MoreUtils qw(pairwise); my @nums = (1, 2, 4, 5, 8, 9); my @dat = (3, 9, 14, 10, 12, 8); print pairwise { "$a $b\n" } @nums, @dat;


Comment on Re: how to print two array with new line at end of each second array element, using a single print statement?
Select or Download Code
Re^2: how to print two array with new line at end of each second array element, using a single print statement?
by davido (Archbishop) on Apr 21, 2012 at 06:48 UTC

    I was just about to follow up with that pairwise option. Glad I saw your update before I did. But I still wanted to mention that I find it necessary to write it something like this:

    print pairwise{ no warnings 'once'; "$a $b\n" } @nums, @dat;

    ...lest I get a pair of warnings that $a and $b are used only once.

    List::MoreUtils provides several ways to do it. This isn't quite as elegant, but still seemed neat to me.

    my $ea = each_array( @nums, @dat ); while( my( $n, $d ) = $ea->() ) { print "$n $d\n"; }

    Update: I've submitted a patch and a corresponding test targeting the 'used only once' warnings.


    Dave

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://966313]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (10)
As of 2015-07-06 21:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (83 votes), past polls