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

I have a variable that contains a path:
my $path = "C:/temp/stuff";
and i have an array that contains a bunch of paths:
open (PATH, "c:/logs/paths.txt"); my @directories = <PATH>; close (PATH);
What is the best way to see if @directories contains $path? The way i'm trying to do it now is:
foreach (@directories) { if ($path eq $_) { stuff } }

Edit by myocom (added code tags)

Replies are listed 'Best First'.
Re: searching an array?
by Biker (Priest) on Mar 15, 2002 at 12:20 UTC

    If you want to act upon one or more occurences of $path in @directories, then you're right on target. In your case, you might want to exit the loop when you have a hit, but that depends upon if you expect to have the same path in your @directories more than once.

    grep() is good for this stuff as well, but only if you want to create a new array with all scalars from @directories that match your $path. (I.e. a subset of @directories)

    map() is fine if you want to create a new array with all scalars from @directories but you want to conditionally make changes to some or all scalars before they go into your new array.

    Do not use grep() or map() unless you intend to use the array returned. (This is in the FAQ. Read it.)


    Everything will go worng!

Re: searching an array?
by broquaint (Abbot) on Mar 15, 2002 at 12:22 UTC
    A good way would be to use grep() to find if @directories contains $path.
    print q[@directories has $path] if grep $_ eq $path, @directories;
    But if you want to do something each time you encounter $path in @directories you might want to use this approach
    foreach (grep $_ eq $path, @directories) { # your code here }
    If you're reading @directories from a file you'll probably want to remove the line endings with a chomp() otherwise $path won't match.
    HTH

    broquaint

Re: searching an array?
by rdfield (Priest) on Mar 15, 2002 at 12:11 UTC
Re: searching an array?
by Parham (Friar) on Mar 15, 2002 at 16:22 UTC
    if ( grep(/^$path$/, @directories) ) { #exact input to array element s +earch print "$path exists in the array of directories"; }
    that's how i'd do it. If grep() gets anything (in the conditional if statement), the program will tell you that your input exists in the array. If you want partial searches in the array, remove the ^ or $ or both depending on whether you want your input to exist in the beginning or the ending or anywhere of each array element.
      Thanks everyone! That did the trick. You guys are fast!