Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: Array searching, grep, first

by ChrisR (Hermit)
on Sep 01, 2005 at 17:46 UTC ( [id://488438]=note: print w/replies, xml ) Need Help??


in reply to Array searching, grep, first

I'll agree that it would probably be more efficient to create a hash and work with that, however here is a way to get the array index using grep
#!c:\perl\bin\perl.exe -w use strict; my @csvlist = qw(file3 file6 file1 file10 file5 file2 file7 file4 file +9 file8); my @listofnames = qw(file1 file2 file3 file4 file5); for my $x(@listofnames) { my ($test) = grep { $csvlist[$_] =~ /$x/} 0..$#csvlist; print "$x found at index: $test\n"; }
That is, if I understood your question correctly.

Update
Here is the output from the test script above:

file1 found at index: 2 file2 found at index: 5 file3 found at index: 0 file4 found at index: 7 file5 found at index: 4
Update: diotalevi makes a good point below about the inefficient use of grep that I displayed above.

Replies are listed 'Best First'.
Re^2: Array searching, grep, first
by diotalevi (Canon) on Sep 01, 2005 at 19:02 UTC

    If you're going to use grep that way, you're doing unnecessary work. Either rewrite that grep as a for loop or use List::Util::first.

    my $index; for ( 0 .. $#csvlist ) { if ( $csvlist[$_] =~ /$x/ ) { $index = $_; last; } } use List::Util 'first'; my $index = first { $csvlist[$_] =~ /$x/ } 0 .. $#csvlist
      You are quite right. grep will search through the entire list on every iteration. first is the way to go but your looping through the indexes is more self explanatory.
Re^2: Array searching, grep, first
by jimbus (Friar) on Sep 01, 2005 at 18:13 UTC

    There are usually 90-120 lines in the CSV per day, so I'm not sure it matters.

    Can I get a little explaination on whats going on with grep { $csvlist[$_] =~ /$x/} 0..$#csvlist; it looks like it would be useful.

    Jimbus

    Never moon a werewolf!
      What's going on here is that the list that is being greped consists of the numbers 0..$#csvlist. (Or zero through the highest index in the array.) The conditional inside the grep block looks at the array item indexed at each number and returns that number if the condition is true.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (4)
As of 2024-04-25 13:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found