perl qstn...

Giorgos Keramidas keramida at ceid.upatras.gr
Tue Apr 6 14:22:15 UTC 2010


On Sun, 04 Apr 2010 02:01:53 -0700, Gary Kline <kline at thought.org> wrote:
> thanks for your url as well and the others to posted.  but it seems
> like overkill since i dont need any explicit option or argument.  i
> just need the script to tell me whether i have an arg or not.
> following is something i've kept in one of my junk drawers from when i
> was learning to write bourne sscripts.  it uses the "$[token]" syntax
> that determines whether there are Any args on the cmdline.  if not,
> the script prints a message and exits.
>
> #!/bin/sh
> if [ $# -eq 0 ]
> then
>         echo "No args; need filename."
> else
>         echo "$1"
> fi
>
> After a couple hours experimentation, the following does the same for my
> perl scripts:
>
>
> #!/usr/bin/perl
> $argc = @ARGV;
> if (! $argc ) {
>         printf("No args; need filename.\n");
> }
> else {
>         printf("%s\n", @ARGV);
> }

Yes, that's very close to the sh(1) version.  Perl's behavior in this
case is described in the 'perlvar' manpage:

       @ARGV   The array @ARGV contains the command-line arguments intended
               for the script.  $#ARGV is generally the number of
               arguments minus one, because $ARGV[0] is the first
               argument, not the program's command name itself.  See $0
               for the command name.

In other words, when @ARGV appears in "scalar context" it yields the
'size' of the @ARGV array, e.g.:

    % cat foo.pl
    printf("%d .. args = [%s]\n", int(@ARGV), join(', ', (@ARGV)));

    % perl foo.pl
    0 .. args = []

    % perl foo.pl 1
    1 .. args = [1]

    % perl foo.pl 1 2 3
    3 .. args = [1, 2, 3]

So when int(@ARGV) is zero you know that there are no arguments at all.

This means you can write your sh version like this in Perl:

    #!/usr/bin/perl

    if (int(@ARGV) == 0) {
        die "No args; at least one filename expected";
    }
    printf("%s\n", join(' ', (@ARGV)));

This is "good enough" as a command-line handling trick for really simple
scripts, but you should probably have a look at the Getopt::Std and the
Getopt::Long modules for longer scripts.  Using them will make your
option parsing code much cleaner and easier to change in the future.



More information about the freebsd-questions mailing list