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

if i provide a directory name to perl program i want to get all files having .sh extention also check all other files not having .sh extention.open these files check first line.if it is #!/usr/local/bin/perl then also display that file name.

Replies are listed 'Best First'.
Re: perl File handling
by tirwhan (Abbot) on Dec 24, 2005 at 07:26 UTC

    I agree with prasadbabu and sub_chick, you should at least attempt this on your own and then show what you have when asking for help.

    Then again, it's that time of the year, so here you are and happy holidays :-)

    #!/usr/bin/perl use warnings; use strict; my $dir; if(!($dir = $ARGV[0]) || !(-d $dir) || !(-x $dir)) { die "Usage: <scriptname> readable_directory\n"; } opendir(my $dh,$dir) or die "Couldn't open $dir"; my @scripts; EXAMINEFILES: while (my $file = readdir($dh)) { if (!(-f $file)) { next EXAMINEFILES; } if ($file =~ m/\.sh$/) { push @scripts,$file; next EXAMINEFILES; } open(my $fh,"<",$file) or die "Couldn't open file $file for readin +g"; my $firstline = (<$fh>); if ($firstline && $firstline =~ m{^\#\!/usr/local/bin/perl}) { push @scripts,$file; } close $fh or die "Couldn't close file $file"; } closedir $dh or die "Couldn't close directory handle"; print "Found the following scripts in $dir:\n"; print join("\n",@scripts)."\n";

    Update: Removed PrivoxyWindow, thanks john


    Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -- Brian W. Kernighan

      The instance of PrivoxyWindowOpen should just be open - looks like Privoxy strikes again ;-)

      Non-Privoxy users, see here for further details.

Re: perl File handling
by sub_chick (Hermit) on Dec 24, 2005 at 06:48 UTC
    I think it would do more good if you showed us at least a starter script to show somewhat of an effort. If you haven't a small code written up yet, then from your question I suggest that you read up on perlman:perlre and File Input and Output.

    "Es gibt mehr zu Leben als Bücher, kennen Sie. Aber nicht viel mehr " -(Der Smiths)
Re: perl File handling
by prasadbabu (Prior) on Dec 24, 2005 at 05:32 UTC

    Do you need Good Christmas Cake?

    Put some effort.

    Prasad