Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

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.


Comment on Re: Beginner question
Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (12)
As of 2015-07-02 10:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (34 votes), past polls