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

I have a script that needs to take @ARGS or the "<" redirect.

%perl script.pl 7 12 5 or %perl script.pl < text.txt #where the contents of the text file are 7 +12 5

If there aren't @ARGS or a "< text.txt" I need it to print a message saying "use args or <".

I think I'm on the right track but I can't really get it to work.

Here's my code:
if(@ARGV) { my @node_numbers= @ARGV} else { my @node_numbers = do { local $/; split ' ', <> };} if (!@node_numbers) { print <<"EOF"; ##################################### # # use args or < a text file # ##################################### EOF die; } # Do rest of code after here using @node_numbers
This is an addon to an older semi-related node

Replies are listed 'Best First'.
Re: File to take @ARGS or "<" Redirect
by ikegami (Patriarch) on Apr 20, 2005 at 19:41 UTC

    If you're really asking how to detect if STDIN is a terminal (when @ARGV is empty), I think the following works:

    my @node_numbers; if (@ARGV) { @node_numbers = @ARGV; } else { die(<<"EOF") if -t STDIN; ##################################### # # use args or < a text file # ##################################### EOF { local $/; @node_numbers = split(' ', <STDIN>); } } # Do rest of code after here using @node_numbers
      Perfect! That's exactly what I needed!!!!!!

      Awesome you guys are always a great help!!!
        which one did the trick? Don't keep us in suspense. Sorry, didnt realize how that sounded when I wrote it.

        Ted
Re: File to take @ARGS or "<" Redirect
by Roy Johnson (Monsignor) on Apr 20, 2005 at 19:35 UTC
    You've scoped @node_numbers local to the blocks of the if. The @node_numbers you're using outside those blocks is not the same variable (it's a global -- you should use strict;).

    Once you fix that, if you run it from the command line, it's going to try to get data from STDIN, which will generally be the keyboard. You'll get the error-out if you redirect from /dev/null.


    Caution: Contents may have been coded under pressure.
      @node_numbers should be global. So I'll do use strict
Re: File to take @ARGS or "<" Redirect
by tcf03 (Deacon) on Apr 20, 2005 at 19:38 UTC
    is this what you mean?
    #!/usr/bin/perl die("no arg!") unless $ARGV[0]; print "\$ARGV[0] = $ARGV[0]\n";


    Ted