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

Hey,

I need to write a perl script that searches for a file from standard input and then opens the file along with line numbers to the left of every line.. Been sitting for hours but haven't got it to work. Tips?

I managed to get it work with the help of: system("find -type f -iname '$filename' -print -exec cat -n {} +"); but that is not pure perl code.

Replies are listed 'Best First'.
Re: School assignment
by thanos1983 (Parson) on Sep 20, 2014 at 01:48 UTC

    Hello mb92,

    I think you answer lies on File::Find. There is a really easy to follow tutorial that practically gives the answer to your question here Beginners guide to File::Find.

    The way that I would solve your problem would be something like:

    print "Enter a file to look up for: "; my $file = <STDIN>; chomp $file; # Get rid of newline character exit 0 if ($file eq ""); # If empty string, exit. use File::Find; my $dir = # whatever you want the starting directory to be find(\&do_something_with_file, $dir); sub do_something_with_file { #.....count number of lines of the file and simply concatenate the + lines. #.....$numlines[$i++] . each line etc. etc. }

    Hope this helps.

    Seeking for Perl wisdom...on the process of learning...not there...yet!
Re: School assignment
by karlgoethebier (Abbot) on Sep 20, 2014 at 12:21 UTC

    I would do it like this:

    #!/usr/bin/env perl + use strict; use warnings; use IO::All; my $file = shift || die qq(No file specified!); my @lines; my $line = 1; my @found = grep { $_->name =~ /.+\/$file$/i } io(q(.))->all; die qq($file not found) unless @found; @lines = map { $_ = $line++ . qq( $_) } io( $found[0] )->slurp; print for @lines; __END__ 1 #!/usr/bin/env perl 2 3 use strict; 4 use warnings; 5 use IO::All; 6 7 my $file = shift || die qq(No file specified!); 8 my @lines; 9 my $line = 1; 10 11 my @found = grep { $_->name =~ /.+\/$file$/i } io(q(.))->all; 12 13 die qq($file not found) unless @found; 14 15 @lines = map { $_ = $line++ . qq( $_) } io( $found[0] )->slurp; 16 17 print for @lines; 18 19 __END__ 20 21

    Please see also IO::All, grep, map and TMTOWTDI.

    Regards, Karl

    «The Crux of the Biscuit is the Apostrophe»

Re: School assignment ( File::Finder )
by Anonymous Monk on Sep 20, 2014 at 06:47 UTC

    I need to write a perl script that searches for a file from standard input and then opens the file along with line numbers to the left of every line.. Been sitting for hours but haven't got it to work. Tips?

    Show your code ?

    I managed to get it work with the help of: system("find -type f -iname '$filename' -print -exec cat -n {} +"); but that is not pure perl code.

    CPAN can make it pure perl code , like find2perl, File::Finder, findrule