Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: Open a folder

by nithins (Sexton)
on Jan 08, 2013 at 10:03 UTC ( #1012211=note: print w/ replies, xml ) Need Help??


in reply to Open a folder

use opendir function , it will help i belive for example

#!/usr/bin/perl use strict; use warnings; my $dir ="./files"; opendir ( DIR, $dir ) || die "Error in opening dir $dir\n"; while( (my $filename = readdir(DIR))){ print "$filename\n"; open (FH,'<',"./files/$filename"); while(<FH>){ ##do your task here} }


Comment on Re: Open a folder
Download Code
Re^2: Open a folder
by Lotus1 (Chaplain) on Jan 08, 2013 at 14:39 UTC

    Your use of a global filehandle 'FH' inside a loop isn't a great idea. If the open fails then the nested while loop will use the already open handle FH which was left open to whatever file was opened last. Also since you've taken the trouble to define $dir why not use it when you open the file?

    open (my $fh,'<',"$dir/$filename") or die " ... $!";

    Another thing to watch out for is the directories '.' and '..'. Your code will pass these into $filename and attempt to open them. Use the file test -d $filename to skip directories. Or use -T $filename to find text files and ignore everything else.

    A final suggestion is to use indentation inside loops and control blocks to help you keep track of the open and close curly braces.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (14)
As of 2014-12-17 20:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (33 votes), past polls