in reply to Search Directory

If you want to exit a loop, use last instead of exit, which exits your program. The following should do what you want, if I understand your question properly.

foreach(@files){ last if $_ eq $img_name; print $_,"\n"; }

If you need to do more complex or recursive searching, check out File::Find.

Update: Fixed typo. (Thanks Grundle :) )

Replies are listed 'Best First'.
Re^2: Search Directory
by Grundle (Scribe) on Feb 01, 2005 at 18:28 UTC
    Your code has an extra curly brace (bug) :p but your analysis of the problem is correct. To explain a little further when you use the last command it will set the position pointer of the array you are traversing to the last entry, which of course means that the array has been fully "traversed" or that there are no more elements to look at.

    The code without the bug would be

    foreach(@files){ if($_ eq $img_name){ last; } print "$_\n"; }
    I hope that helps, good luck
      The code still does the line print "$_\n";
      even if if($_ eq $img_name) this condition is true.
      I would like the code to exit the foreach completely.
      Thanks.
        There is nothing wrong with the code. I did a UNIT TEST just to make sure. Try running the following and you will notice that it exits out and does not print when the

        if($_ eq $img_name)

        statement is reached.

        @array = (0, 1, 2, 3, 4, 5); foreach(@array){ if($_ eq 3){ last; } print "$_\n"; } #this will output #0 #1 #2
        Try checking to make sure $img_name is what you think it is, or it may be that the defined $img_name is not contained within the file and therefore no match will be made?