Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: question on File::Find (cd)

by tye (Cardinal)
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        


Comment on Re: question on File::Find (cd)
Download Code
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.

        thanks

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (11)
As of 2014-09-19 09:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (133 votes), past polls