Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

Re: Beginner question

by thezip (Vicar)
on Jul 11, 2008 at 16:00 UTC ( #696995=note: print w/replies, xml ) Need Help??

in reply to Beginner question

nukeboy, I've made a few modifications to your code. If you have any questions about why I did something, just ask away!

#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my $dir_to_process = '.'; my %stuff_to_store; # Get all of the txt files and put them into the @files array opendir(DH, $dir_to_process) or die "Cannot open $dir_to_process: $!"; my @files = grep { /\.txt$/i } readdir(DH); closedir(DH); my $fullname = "$dir_to_process/$file"; # Process each file for my $file (@files) { open(my $fh, "<", $fullname) or die(qq(Unable to open '$fullname' fo +r reading: $!); # I like to explicitly set a $line variable, rather than implicitly +using $_ while (my $line = <$fh>) { #cycling through to find happy if ($line =~ /happy/) { # Here, I'm using %stuff_to_store as a hash of array references # The hash key is the concatenation of the path and the file nam +e # The value for each key is an array reference that contains lin +es # like: # "Line 123: <this is the text of the found line>" push(@{$stuff_to_store{$fullname}, "Line $.: $line"); } } close ($fh); } print Dumper(\%stuff_to_store);

BTW, this code is untested, so please forgive any errors.

Update: As pc88mxer dutifully pointed out to me, I neglected to qualify the full path to the file when I was opening it. This has been corrected.

Your wish is my commandline.

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (4)
As of 2018-05-25 09:27 GMT
Find Nodes?
    Voting Booth?