[Chicago-talk] Q on '-n'

Mike Pastore mike at oobak.org
Tue Sep 16 04:53:37 CDT 2003


Hi Walter,

Certainly, you are close! But I might offer some suggestions. To answer
your last email first, it is easy enough to check @ARGV in your BEGIN
statement:

    BEGIN
    {
        die "usage: $0 -o <output> <input 1> <input 2> ... <input n>\n" 
            unless @ARGV > 2;
        ...

Or perhaps check after you trim out your option. I might also recommend
the -s switch in this case, as in the following:

    #!/usr/bin/perl -n -s

    BEGIN
    {
        die "usage: ... \n" unless @ARGV and defined $o;

        open(TEMP, ">>$o") 
            or die "Unable to open '$o' for writing: $!\n";
    }

    print TEMP; 

There is no need to close any filehandles. Your data is coming from
STDIN. You may close TEMP in an END block if you wish, but it is
unnecessary.

Regarding style (and your future goal of letting the user specify a
directory), consider letting user's shell do all the hard work. For
example,

   $ perl -pe';' file1 file2 >> file3
   $ perl -ne'print if /foo/' dir1/* > file3

Of course, it all depends on the program you're writing. This may not be
a feasible solution to your problem. But I thought I'd mention it,
because it might save you time! When writing little scripts like this I
prefer to let UNIX do all the grunt work of listing directories and
pushing data around, instead of opening file handles left and right.
Also, if you use STDOUT and STDERR it gives the user freedom to act on
the output as s/he sees fit. FWIW.

--
Mike Pastore
mike at oobak.org

----- Original message -----
From: "Walter Torres" <walter at torres.ws>
To: "Chicago.pm chatter" <chicago-talk at mail.pm.org>
Date: Tue, 16 Sep 2003 02:14:39 -0500
Subject: [Chicago-talk] Q on '-n'

I'm trying to figure out how to utilize '-n' best.

I have a cmd line...

   myScript.pl file_1.txt file_2.txt -o result.out

I want to cycle through all file[s] given by the cmd line (if it's a
path,
all the files in that dir, but that's for later) and spit the results
(whatever it may be) into the file given via the '-o' parameter.

My test script (see below)

Is this the best way to accomplish this?

Thanks for your help.

Walter


==================================================

#!/usr/local/bin/perl -n

BEGIN
{
   # place entire cmd line into single scalar
   $arg = join ' ', @ARGV;

   # split off the inbound file(s) and the result file
   ($arg, $outFile) = split '-o', $arg;

   # rebuilt the cmd line
   @ARGV = split ' ', $arg;

   # Open given tmp file
   open( TEMP, ">>$outFile")
			or die "No Way! \n$!\n$outFile\n";
}

# loop begins here
print TEMP "$ARGV: $.\n";

# clode the file when we are done with it
close ARGV if eof;

# eof


_______________________________________________
Chicago-talk mailing list
Chicago-talk at mail.pm.org
http://mail.pm.org/mailman/listinfo/chicago-talk



More information about the Chicago-talk mailing list