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

I call a perl .pl file with command line arguments. When this file starts to execute, I can retrieve the passed values, if I do it from the main program. If I try to do it from a subroutine in a package, I can't. I'd really rather do it from the subroutine. Is there a way to fix this? Thanks, John Bobinyec

Replies are listed 'Best First'.
Re: Scope of ARGV
by ikegami (Patriarch) on Nov 28, 2011 at 18:40 UTC

    Are you sure you don't empty @ARGV before trying to use it in the sub? What you say doesn't appear to be true.

    >perl -E"Foo::foo(); package Foo; sub foo { say for @ARGV }" a b c a b c

    @ARGV is global, even using it's unqualified name. You could also use its fully qualified name, but it's not necessary.

    >perl -E"Foo::foo(); package Foo; sub foo { say for @::ARGV }" a b c a b c

    @::ARGV is also known as @main::ARGV.

      My mistake. I was doing a call to "getopts" , forgetting that it strips ARGV clean. Thanks, John Bobinyec

Re: Scope of ARGV
by davido (Cardinal) on Nov 28, 2011 at 18:28 UTC

    @main::ARGV


    Dave

Re: Scope of ARGV
by toolic (Bishop) on Nov 28, 2011 at 18:39 UTC
    I can access @ARGV from a sub in a package from a separate script:
    $ cat Foo.pm package Foo; sub p { print "@ARGV\n" } 1; $ $ cat foo.pl #!/usr/bin/env perl use Foo; Foo::p(); $ ./foo.pl abc 123 abc 123 $
    Do you get errors or warnings? Show your code and how you call it.
Re: Scope of ARGV
by chromatic (Archbishop) on Nov 28, 2011 at 18:33 UTC

    Can you post simple test code?

    I've taken to starting my programs with:

    #!/usr/bin/env perl use Modern::Perl; exit main(@ARGV); sub main { my @args = @_; ... exit 0; }

    ... but @ARGV is available by name even within main().


    Improve your skills with Modern Perl: the free book.