in reply to I need help with opening a directory and reading files in that directory.
Brandon,
Welcome to the Monastery. Let's see if we can get your script working as expected - let us break it down one step at a time and solve each problem in turn.
I'm having a hard time creating/reading the files to do something with and create the $hash{$key} = $values. But, is there a way to use <> to open the directory path
We do not use <> when opening a directory path. Here is a small script to open a directory, read the contents of that directory and list/print the files therein
#! perl -slw use strict; opendir DH, "." or die $!; # open current directory while($_ = readdir(DH)){ # don't evaluate special dirs '.' & '..' next if $_ eq "." or $_ eq ".."; print "$_"; # print this file/directory's name } __END__
One can also use a construct known as a glob to evaluate the contents of a directory
#! perl -slw use strict; my @files = glob("*"); print "Files matched via glob pattern *: @files\n"; __END__
and then use the <> to read the files and do something with the information.
Reading files and doing something with the information is relatively straightforward (but beware this can get hairy real fast based on what your particular environment is like - let's keep it simple for now. It's enough that you've been made aware that what we're doing here is scratching the surface).
#! perl -slw use strict; opendir DH, "." or die $!; # open current directory while($_ = readdir(DH)){ # don't evaluate special dirs '.' & '..' next if $_ eq "." or $_ eq ".."; print "$_"; # print this file/directory's name # as a by-product of readdir; use the file's stat info # to check whether this is indeed a regular file we can # open for reading/further processing if (-f $_) { open FH, "<$_" or die $!; print "output for file: $_\n"; while (my $line = <FH>) { print $line; } close FH; } } __END__
Let us know if you have any issues w/ the syntax for using a hash.
p.s. Careful when using RegExps; certain characters carry special meaning and need to be "escaped". So instead of having
if ($filename =~ /.txt/)
You might want to have:
if ($filename =~ /\.txt/)
|
|---|