#!/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' for 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 name # The value for each key is an array reference that contains lines # like: # "Line 123: " push(@{$stuff_to_store{$fullname}, "Line $.: $line"); } } close ($fh); } print Dumper(\%stuff_to_store);