heres another way, tho it still does not use chdir, but it does work from the scripts location and all you have to feed it is the absolute path or from script path as arg.
use strict;
use warnings;
use diagnostics;
use File::Slurp;
#use Cwd;
my @files;
get_args();
sub get_args {
my $dir;
my $string;
print "enter path\n";
chomp( $dir = <STDIN> );
print "enter match string\n";
chomp( $string = <STDIN> );
print "\n";
@files = read_dir($dir);
print $_ for @files ;
traverse( $dir, $string );
}
sub traverse {
foreach my $element (@files) {
open $file, "<", $dir.'/'.$element;
while (<$file>) {
if ( $_ =~ m/$string/i ) {
print "found $string in $element\n";
}
}
close $file;
}
get_args();
}
to me its more manageable if it is broken up in subroutines. that way you can have one function to get the input, then the other to actually collect results.
EDIT: here is the newest code, which i have not really looked any further into this tbh, but you should be able to add chdir and list dir contents pretty easily. Could maybe even add switches for searching cwd for the string you needed.
use strict;
use warnings;
use diagnostics;
use File::Slurp;
#use Cwd;
my @files;
get_args();
sub get_args {
print "enter path: ";
chomp( my $dir = <STDIN> );
print "enter match string: ";
chomp( my $string = <STDIN> );
@files = read_dir($dir);
print "\n", $_ for @files, "\n" ;
traverse( $dir, $string );
}
sub traverse {
my ( $dir, $string ) = @_;
for my $element (@files) {
open (my $file, '<', "$dir/$element") || next;
while (<$file>) {
if ( $_ =~ m/$string/i ) {
print "found $string in $element\n";
}
}
close $file;
}
print "\n";
get_args();
}