tousifp has asked for the wisdom of the Perl Monks concerning the following question:

In a unix directory, I want to get file names wherein I could get a particular string to be searched.

e.g.I could do in unix following :

grep -il "^$input" *

where $input is 2013-09-04

How can I do it in perl?

Thanks

Replies are listed 'Best First'.
Re: To get file names from the search string
by choroba (Cardinal) on Sep 05, 2013 at 14:27 UTC
    grep -il "^$input" *

    is equivalent to the following Perl one-liner in bash:

    perl -lne '$seen{$ARGV} = 1 if /^'"$input/i }{ print for keys %seen" *

    or the following script:

    #!/usr/bin/perl use strict; use warnings; my $input = shift; for my $file (glob '*') { open my $IN, '<', $file or die $!; while (<$IN>) { if (/^$input/i) { print "$file\n"; last; } } }

    Run as script.pl "$input".

    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re: To get file names from the search string
by Corion (Patriarch) on Sep 05, 2013 at 14:08 UTC

    For example with a combination of readdir and grep:

    my $dirname= '/some/directory/with/files'; my $input= '2013-09-04'; opendir my $dh, $dirname or die "Couldn't read '$dirname': $!"; my @found= grep /^\Q$input\E/, readdir $dh; ...

    In my opinion the easiest way is to use File::Glob::bsd_glob:

    use File::Glob qw( bsd_glob ); my @found= bsd_glob("$input*");

      That's not what grep -il is doing, it outputs the filenames of the files whose content contains the string. So IMHO it's easier to use grep, unless there's more to this problem that we know about.