Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

iterating over two arrays

by Anonymous Monk
on Mar 04, 2005 at 16:12 UTC ( #436623=perlquestion: print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I have an array that holds information with which I'd like to apply in a search of another array. @array = ($username, $pass); @array1 = ($user, $info, $info1,$info2); I'd like to know the most efficient way of correlating the info.
foreach my $line(@array) { foreach (@array1) { if ($username eq $user){ print "$line\n"; } } }
That does not seem to me to be good - can anybody show me how to do it?

Thanks

Replies are listed 'Best First'.
Re: iterating over two arrays
by Mugatu (Monk) on Mar 04, 2005 at 17:24 UTC

    You will probably want to load one of the array's values into a hash, keyed on the field you want to correlate them with. It looks like you want to match on username, so that would be your hash key. Here's an abstract example:

    my @foo = ( [ 1, 'foo' ], [ 2, 'bar' ], [ 3, 'baz' ], ); my %bar = ( 1 => [ 'a', 'b', 'c' ], 2 => [ 'd', 'e', 'f' ], 3 => [ 'g', 'h', 'i' ], ); for (@foo) { my ($num, $label) = @{ $_ }; print "$label: ", @{ $bar{$num} }, "\n"; }

    Here, the number is used to correlate the values.

      Mugatu I want to marry you and have your babies (metaphorically speaking, I'm afraid!]

      That's exactly what I'm looking for

      Thanks
Re: iterating over two arrays
by sh1tn (Priest) on Mar 04, 2005 at 16:18 UTC
Re: iterating over two arrays
by saintmike (Vicar) on Mar 04, 2005 at 16:28 UTC
    See perlfaq4:
    How do I compute the difference of two arrays? How do I compute the intersection of two arrays?
    (use this site until perldoc.com or perldoc:// gets fixed).
Re: iterating over two arrays (mapcar)
by tye (Sage) on Mar 04, 2005 at 17:53 UTC

    Algorithm::Loops contains several flavors of MapCar, which lets you iterate through several arrays at once (update:) in parallel, which isn't what was asked for. Sorry.

    - tye        

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (2)
As of 2019-07-21 08:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    If you were the first to set foot on the Moon, what would be your epigram?






    Results (7 votes). Check out past polls.

    Notices?