Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

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

by eyepopslikeamosquito (Archbishop)
on Apr 21, 2012 at 06:32 UTC ( [id://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

Replies are listed 'Best First'.
Re^2: how to print two array with new line at end of each second array element, using a single print statement?
by davido (Cardinal) 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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://966313]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (5)
As of 2024-04-19 17:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found