Skip site navigation (1)Skip section navigation (2)
Date:      Tue, 06 Apr 2010 17:18:59 +0300
From:      Giorgos Keramidas <keramida@ceid.upatras.gr>
To:        kline@thought.org
Cc:        glarkin@FreeBSD.org, FreeBSD Mailing List <freebsd-questions@FreeBSD.org>
Subject:   Re: perl qstn...
Message-ID:  <874ojor7e4.fsf@kobe.laptop>
In-Reply-To: <1270371713.5861.98.camel@tao.thought.org> (Gary Kline's message of "Sun, 04 Apr 2010 02:01:53 -0700")
References:  <20100403210610.GA4135@thought.org> <4BB8108A.9080104@FreeBSD.org> <1270371713.5861.98.camel@tao.thought.org>

next in thread | previous in thread | raw e-mail | index | archive | help
On Sun, 04 Apr 2010 02:01:53 -0700, Gary Kline <kline@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.




Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?874ojor7e4.fsf>