in reply to Poor's man command line arguments

For your first example, this type of command line argument parsing can be carried out more simply with the -s switch to the Perl executable - This argument enables rudimentary switch parsing on the command line after the script name but before any filename arguments (or before a --). Any switch found is removed from @ARGV and a variable with a corresponding name is set.

For example, the following code will print bar! if the command line switch -foo is passed to the script:

#!/usr/bin/perl -s print "bar!\n" if ($foo);

This behaviour is documented in perlrun - For a truly evil use of this behaviour (and Perl in general) have a look at theDamian's selfGOL obfuscation :-)

 

perl -e 'print+unpack("N",pack("B32","00000000000000000000000111011111")),"\n"'

Replies are listed 'Best First'.
Re: Re: Poor's man command line arguments
by Louis_Wu (Chaplain) on Nov 14, 2002 at 01:26 UTC
    How does the use of $foo as a switch jive with the recomendation to use strict; for all programs? Can a switch be localized? Are switches only possible in programs without use strict;? How would switches be declared (?) for use in my program if I do want to use strict;?

    I think I've got some research to do when I get home.

      How does the use of $foo as a switch jive with the recomendation to use strict; for all programs?

      In short, it doesn't - The -s argument is meant for quick-and-nasty argument handling, the usage of these variable names causing explicit package name errors when employed with strict.

      For example:

      rob@budapest:/home/rob# cat test.perl #!/usr/bin/perl -s use strict; print "bar!\n" if ($foo); rob@budapest:/home/rob# ./test.perl -foo Variable "$foo" is not imported at ./test.perl line 5. Global symbol "$foo" requires explicit package name at ./test.perl lin +e 5. Execution of ./test.perl aborted due to compilation errors.
      If however, strict is turned off within the scope where these variables are employed, everything is happy once more. Eg.

      rob@budapest:/home/rob# cat test.perl #!/usr/bin/perl -s use strict; { no strict; print "bar!\n" if ($foo); } rob@budapest:/home/rob# ./test.perl -foo bar!

       

      perl -e 'print+unpack("N",pack("B32","00000000000000000000000111100000")),"\n"'

        If however, strict is turned off within the scope where these variables are employed, everything is happy once more.

        Or use 'use vars' or 'our':

        #!/usr/bin/perl -s use strict; use warnings; use vars qw($foo); print "bar!\n" if $foo;