Fellow monks:

I have a sub-routine that parses a list of files and returns a data structure. I'd like to write a unix-style filter that takes either a list of files from STDIN or a filename(s) on the command line and feeds the list into the sub. The angle operator (<>) looks like the way to go, but I've got a question regarding it's use.

I'm using the following to do this:

#!/usr/bin/perl use strict; use warnings; while ( <> ) { ... }

Doing the following:

ls *.txt | my_script.pl

sticks each file from the ls into $_, allowing me to create a list of files for the sub, but the following:

my_script.pl text.txt

opens the file(s) and reads it line by line, placing each line into $_, which is not what I want. I like to be able to feed @ARGV right into my sub.

So I wrote the following to create the list of files if the user specifies them on the command line:

#!/usr/bin/perl use strict; use warnings; my @files; if ( @ARGV ) { @files = map { -f $_ ? $_ : () } @ARGV; } else { while ( <> ) { chomp; push @files, $_; } }

Is this a clean way to do this (I know, I know: TMTOWTDI) or is there a better way?

njcodewarrior


In reply to Writing unix-style filters by njcodewarrior

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.