Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number

Re: question on File::Find (cd)

by tye (Sage)
on Oct 30, 2012 at 13:40 UTC ( #1001502=note: print w/replies, xml ) Need Help??

in reply to question n File::Find

Why do you open the file just to close it again? You know -r can take a file name, not just a file handle, right?

Putting variables in quotes when you don't need to may bite you in future when you get to using references. But maybe you won't put variables containing references in quotes and so it is just a style issue.

But the main problem with your code is that $File::Find::name will often not be useful for opening a file (nor for checking the permissions on a file).

If you call File::Find's find() and pass it "foo" as the directory to search, then find() will chdir into the "foo" directory (by default) before doing much of any work. If you have a file "foo/bar", then your 'wanted' subroutine will be called with $_ set to "bar" and $File::Find::name set to "foo/bar".

Since your program is now cd'd into "foo", trying to open "foo/bar" would only work if you also had a "foo/foo/bar" file. So try:

sub wanted { print "hello 1\n" if -r $_; }

- tye        

Replies are listed 'Best First'.
Re^2: question on File::Find (cd)
by skyworld_chen (Acolyte) on Oct 31, 2012 at 01:43 UTC

    thank you for your reply. I tried your code and it WORKS! thank you very much and thanks for every one who had replied my questions.

    by the way, I would like to do some operation to the file, I tried some code like this:

    print "hello 1\n" if (-r $_); my @matching = grep {/$my_pattern/} <$_>;

    I failed with this code. I have to

    open $filehandle,"<", $_" or die .... my @matching = grep {/$my_pattern/} <$_>;

    did I do something wrong? or is there any better way to do grep or similar operateion in the $_? thanks.

      Use File::Slurp to read a file in one command.
      Sorry if my advice was wrong.


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1001502]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (11)
As of 2018-06-19 12:11 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (113 votes). Check out past polls.