Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"

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} }

Replies are listed 'Best First'.
Re^2: Open a folder
by Lotus1 (Curate) 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?

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

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (4)
As of 2018-03-18 18:59 GMT
Find Nodes?
    Voting Booth?
    When I think of a mole I think of:

    Results (230 votes). Check out past polls.