Argv - Provide an OO interface to an arg vector


    use Argv;

    # A roundabout way of getting perl's version.
    my $pl = Argv->new(qw(perl -v));

    # Run /bin/cat, showing how to provide "predigested" options.
    Argv->new('/bin/cat', [qw(-u -n)], @ARGV)->system;

    # A roundabout way of globbing.
    my $echo = Argv->new(qw(echo M*));
    my $globbed = $echo->qx;
    print "'echo M*' globs to: $globbed";

    # A demonstration of head-like behavior (aborting early).
    my $maxLinesToPrint = 5;
    my $callback = sub {
        print shift;
        return --$maxLinesToPrint;
    my $head = Argv->new('ls', [qw(-l -a)]);

    # A demonstration of the builtin xargs-like behavior.
    my @files = split(/\s+/, $globbed);
    my $ls = Argv->new(qw(ls -d -l), @files);
    $ls->parse(qw(d l));
    my @long = $ls->qx;
    print @long;

    # A demonstration of how to use option sets in a wrapper program.
    @ARGV = qw(Who -a -y foo -r);       # hack up an @ARGV
    my $who = Argv->new(@ARGV);         # instantiate
    $who->dbglevel(1);                  # set verbosity
    $who->optset(qw(UNAME FOO WHO));    # define 3 option sets
    $who->parseUNAME(qw(a m n p));      # parse these to set UNAME
    $who->parseFOO(qw(y=s z));          # parse -y and -z to FOO
    $who->parseWHO('r');                # for the 'who' cmd
    warn "got -y flag in option set FOO\n" if $who->flagFOO('y');
    print Argv->new('uname', $who->optsUNAME)->qx;
    $who->prog(lc $who->prog);          # force $0 to lower case
    $who->exec(qw(WHO));                # exec the who cmd

More advanced examples can be lifted from the test script or the ./examples subdirectory.


Argv presents an OO approach to command lines, allowing you to instantiate an 'argv object', manipulate it, and eventually execute it, e.g.:

    my $ls = Argv->new('ls', ['-l']));
    my $rc = $ls->system;       # or $ls->exec or $ls->qx

Which raises the immediate question - what value does this mumbo-jumbo add over Perl's native way of doing the same thing:

    my $rc = system(qw(ls -l));

The answer comes in a few parts:


    First, Argv recognizes the underlying property of an arg vector, which is that it begins with a program name potentially followed by options and then operands. An Argv object factors a raw argv into these three groups, provides accessor methods to allow operations on each group independently, and can then paste them back together for execution.


    Second, Argv encapsulates and extends Getopt::Long to allow parsing of the argv's options into different option sets. This is useful in the case of wrapper programs which may, for instance, need to parse out one set of flags which direct the behavior of the wrapper itself, extract a different set and pass them to program X, another for program Y, then exec program Z with the remainder. Doing this kind of thing on a basic @ARGV using indexing and splicing is do-able but leads to spaghetti-ish code.


    The execution methods system, exec, qx, and pipe extend their Perl builtin analogues in a few ways, for example:

    1. An xargs-like capability without shell intervention.
    2. UNIX-like exec() behavior on Windows.
    3. Automatic quoting of system() on Win32 and qx()/pipe() everywhere.
    4. Automatic globbing (primarily for Windows).
    5. Automatic chomping.
    6. Pathname normalization (primarily for Windows).

All of these behaviors are optional and may be toggled either as class or instance attributes. See EXECUTION ATTRIBUTES below.


An Argv object treats a command line as 3 separate entities: the program, the options, and the args. The options may be further subdivided into user-defined option sets by use of the optset method. When one of the execution methods is called, the parts are reassembled into a single list and passed to the underlying Perl execution function.

Compare this with the way Perl works natively, keeping the 0th element of the argv in $0 and the rest in @ARGV.

By default there's one option set, known as the anonymous option set, whose name is the null string. All parsed options go there. The advanced user can define more option sets, parse options into them according to Getopt::Long-style descriptions, query or set the parsed values, and then reassemble them in any way desired at exec time. Declaring an option set automatically generates a set of methods for manipulating it (see below).

All argument-parsing within Argv is done via Getopt::Long.


Argv employs the same technique made famous by the Shell module to allow any command name to be used as a method. E.g.


will run the 'date' command. Internally this is translated into


See the argv method below.


Because the extensions to system/exec/qx described above may be helpful in writing portable programs, the methods are also made available for export as traditional functions. Thus:

    use Argv qw(system exec qv pipe);

will override the Perl builtins. There's no way (that I know of) to override the operator qx() so an alias qv() is provided.


    my $obj = Argv->new(@list)

The @list is what will be parsed/executed/etc by subsequent method calls. During initial construction, the first element of the list is separated off as the program; the rest is lumped together as part of the args until and unless option parsing is done, in which case matched options are shifted into collectors for their various option sets. You can also create a "predigested" instance by passing any or all of the prog, opt, or arg parts as array refs. E.g.

    Argv->new([qw(cvs ci)], [qw(-l -n)], qw(file1 file2 file3));

Predigested options are placed in the default (anonymous) option set.

The constructor can be used as a class or instance method. In the latter case the new object is a deep (full) clone of its progenitor. In fact there's a clone method which is an alias to new, allowing clones to be created via:

        my $copy = $orig->clone;

The first argument to new() or clone() may be a hash-ref, which will be used to set execution attributes at construction time. I.e.:

    my $obj = Argv->new({autochomp => 1, stderr => 0}, @ARGV);

You may choose to create an object and add the command line later:

    my $obj = Argv->new;


    my $obj = Argv->new({autochomp=>1});
    my $motd = $obj->argv(qw(cat /etc/motd))->qx;

Or (using the autoloading interface)

    my $motd = $obj->cat('/etc/motd')->qx;



  • prog()

    Returns or sets the name of the program (the "argv[0]"). The argument may be a list, e.g. qw(rcs co) or an array reference.

  • opts()

    Returns or sets the list of operands (aka arguments). As above, it may be passed a list or an array reference. This is simply the member of the class of optsNAME() methods (see below) whose <NAME> is null; it's part of the predefined anonymous option set.

  • args()

    Returns or sets the list of operands (aka arguments). If called in a void context and without args, the effect is to set the list of operands to ().

  • argv()

    Allows you to set the prog, opts, and args in one method call. It takes the same arguments as the constructor (above); the only difference is it operates on a pre-existing object to replace its attributes. I.e.

        my $obj = Argv->new;
        $obj->argv('cmd', [qw(-opt1 -opt2)], qw(arg1 arg2));

    is equivalent to

        my $obj = Argv->new('cmd', [qw(-opt1 -opt2)], qw(arg1 arg2));

    Without arguments, returns the current arg vector as it would be executed:

        my @cmd = $ct->argv;
  • optset(<list-of-set-names>);

    For each name NAME in the parameter list, an option set of that name is declared and 3 new methods are registered dynamically: parseNAME(), optsNAME(), and flagNAME(). These methods are described below: note that the anonymous option set (see OPTION SETS) is predefined, so the methods parse(), opts(), and flag() are always available. Most users won't need to define any other sets. Note that option-set names are forced to upper case. E.g.:

  • parseNAME(...option-descriptions...)

    Takes a list of option descriptions and uses Getopt::Long::GetOptions() to parse them out of the current argv and into option set NAME. The opt-descs are exactly as supported by parseFOO() are exactly the same as those described for Getopt::Long, except that no linkage argument is allowed. E.g.:

        $obj->parseFOO(qw(file=s list=s@ verbose));
  • optsNAME()

    Returns or sets the list of options in the option set NAME.

  • flagNAME()

    Sets or gets the value of a flag in the appropriate optset, e.g.:

        print "blah blah blah\n" if $obj->flagFOO('verbose');
        $obj->flagFOO('verbose' => 1);
  • extract

    Takes an optset name and a list of option descs; creates the named optset, extracts any of the named options, places them in the specified optset, and returns them.

  • quote(@list)

    Protects the argument list against exposure to a shell by quoting each element. This method is invoked automatically by the system method on Windows platforms, where the underlying system primitive always uses a shell, and by the qx method on all platforms since it invokes a shell on all platforms.

    The automatic use of quote can be turned off via the autoquote method (see).

    IMPORTANT: this method quotes its argument list in place. In other words, it may modify the arguments.

  • glob

    Expands the argument list using the Perl glob builtin. Primarily useful on Windows where the invoking shell does not do this for you.

    Automatic use of glob on Windows can be enabled via the autoglob method (vide infra).

  • objdump

    A no-op except for printing the state of the invoking instance to stderr. Potentially useful for debugging in situations where access to perl -d is limited, e.g. across a socket connection or in a crontab. Invoked automatically at dbglevel=3.

  • readonly

    Sets/gets the "readonly" attribute, which is a string indicating whether the instance is to be used for read operations only. If the attribute's value starts with y, execution methods will be allowed to proceed even if the $obj->noexec attribute is set.

    The value of this is that it enables your script to have a -n flag, a la make -n, pretty easily by careful management of ->readonly and ->noexec. Consider a script which runs ls to determine whether a file exists and then, conditionally, uses rm -f to remove it. Causing a -n flag from the user to set ->noexec alone would break the program logic since the ls would be skipped too. But, if you take care to use objects with the readonly attribute set for all read-only operations, perhaps by defining a special read-only object:

            my $ro = Argv->new;

    then the -n flag will cause only write operations to be skipped.

    Note that, if you choose to use this feature at all, determining which operations are readonly is entirely the programmer's responsibility. There's no way for Argv to determine whether a child process will modify state.


The three methods below are direct analogues of the Perl builtins. They simply reassemble a command line from the prog, opts, and args parts according to the option-set rules described below and invoke their builtin equivalent on it.

  • system([<optset-list>])

    Reassembles the argv and invokes system(). Return value and value of $?, $!, etc. are just as described in perlfunc/"system"

    Arguments to this method determine which of the parsed option-sets will be used in the executed argv. If passed no arguments, $obj->system uses the value of the 'dfltsets' attribute as the list of desired sets. The default value of 'dfltsets' is the anonymous option set.

    An option set may be requested by passing its name (with an optional leading '+') or explicitly rejected by using its name with a leading '-'. Thus, given the existence of option sets ONE, TWO, and THREE, the following are legal:

        $obj->system;                       # use the anonymous set only
        $obj->system('+');                  # use all option sets
        $obj->system(qw(ONE THREE);         # use sets ONE and THREE

    The following sequence would also use sets ONE and THREE.

        $obj->dfltsets({ONE => 1, THREE => 1});

    while this would use all parsed options:

        $obj->dfltsets({'+' => 1});

    and this would set the default to none class-wide, and then use it:

        $obj->dfltsets({'-' => 1});

    By default the $obj->system method autoquotes its arguments iff the platform is Windows and the arguments are a list, because in this case a shell is always used. This behavior can be toggled with $obj->autoquote.

  • exec([<optset-list>])

    Similar to system above, but never returns. On Windows, it blocks until the new process finishes for a more UNIX-like behavior than the exec implemented by the MSVCRT, if the execwait attribute is set. This is actually implemented as


    on Windows, and thus all system shell-quoting issues apply

    Option sets are handled as described in system above.

  • qx([<optset-list>])

    Same semantics as described in perlfunc/"qx" but has the capability to process only a set command line length at a time to avoid exceeding OS line-length limits. This value is settable with the qxargs method.

    One difference from the builtin perlfunc/"qx" is that the builtin allows you to leave off the double quotes around the command string (though they are always there implicitly), whereas the qv() functional interface must use literal quotes. For instance, using qx() you can use either of:

        my @results = qx(command string here);
        my @results = qx("command string here");

    which are semantically identical, but with qv() you must use the latter form.

    Also, if autoquote is set the arguments are escaped to protect them against the platform-standard shell on all platforms.

    Option sets are handled as described in system above.

  • pipe([<optset-list>])

    Provides functionality to use the 'open' process pipe mechanism in order to read output line by line and optionally stop reading early. This is useful if the process you are reading can be lengthy but where you can quickly determine whether you need to let the process finish or if you need to save all output. This can save a lot of time and/or memory in many scenarios.

    You must pass in a callback code reference using ->pipecb. This callback will receive one line at a time (autochomp is active). The callback can do whatever it likes with this line. The callback should return a false value to abort early, but for this to be honored, the Argv instance should be marked 'readonly' using the ->readonly method. A default callback is in effect at start that merely prints the output.

    ->pipe is otherwise similar to, and reuses settings for qx (except for the ability to limit command line lengths).

    Without exhaustive testing, this is believed to work in a well-behaved manner on Unix.

    However, on Windows a few caveats apply. These appear to be limitations in the underlying implementation of both Perl and Windows.

    1. Windows has no concept of SIGPIPE. Thus, just closing the pipe handle will not necessarily cause the child process to quit. Bummer :-(.
    2. Sometimes an extra process is inserted. For example, if stderr has been redirected using $obj->stderr(1) (send stderr to stdout), this causes Perl to utilize the shell as an intermediary process, meaning that even if the shell process quits, its child will continue.

    For the above reasons, in case of an abort request, on Windows we take it further and forcibly kill the process tree stemming from the pipe. However, to make this kill the full tree, some nonstandard packages are required. Currently any of these will work:

  • Win32::Process::Info

  • Win32::ToolHelp

    Both are available as PPM packages for ActiveState perls, or on CPAN.


The behavior of the execution methods system, exec, and qx is governed by a set of execution attributes, which are in turn manipulated via a set of eponymous methods. These methods are auto-generated and thus share certain common characteristics:

  • Translucency

    They can all be invoked as class or instance methods. If used as an instance method the attribute is set only on that object; if used on the class it sets or gets the default for all instances which haven't overridden it. This is inspired by the section on translucent attributes in Tom Christiansen's perltootc tutorial.

  • Class Defaults

    Each attribute has a class default which may be overridden with an environment variable by prepending the class name, e.g. ARGV_QXARGS=256 or ARGV_STDERR=0;

  • Context Sensitivity

    The attribute value is always a scalar. If a value is passed it becomes the new value of the attribute and the object or class is returned. If no value is passed and there is a valid return context, the current value is returned. In a void context with no parameter, the attribute value is set to 1.

  • Stickiness (deprecated)

    A subtlety: if an execution attribute is set in a void context, that attribute is "sticky", i.e. it retains its state until explicitly changed. But if a new value is provided and the context is not void, the new value is temporary. It lasts until the next execution method (system, exec, or qx) invocation, after which the previous value is restored. This feature allows locutions like this:


    Assuming that the $obj object already exists and has a set of attributes; we can override one of them at execution time. The next time $obj is used, stderr will go back to wherever it was directed before. More examples:

            $obj->stdout(1);          # set attribute, sticky
            $obj->stdout;             # same as above
            $foo = $obj->stdout;      # get attribute value
            $obj2 = $obj->stdout(1);  # set to 1 (temporary), return $obj

    WARNING: this attribute-stacking has turned out to be a bad idea. Its use is now deprecated. There are other ways to get to the same place: you can maintain multiple objects, each of which has different but permanent attributes. Or you can make a temporary copy of the object and modify that, e.g.:


    each of which will leave $obj unaffected.

  • autochomp

    All data returned by the qx or pipe methods is chomped first. Unset by default.

  • autofail

    When set, the program will exit immediately if the system, qx, or pipe methods detect a nonzero status. Unset by default.

    Autofail may also be given a code-ref, in which case that function will be called upon error. This provides a basic exception-handling system:

        $obj->autofail(sub { print STDERR "caught an exception\n"; exit 17 });

    Any failed executions by $obj will result in the above message and an immediate exit with return code == 17. Alternatively, if the reference provided is an array-ref, the first element of that array is assumed to be a code-ref as above and the rest of the array is passed as args to the function on failure. Thus:

        $obj->autofail([&handler, $arg1, $arg2]);

    Will call handler($arg1, $arg2) on error. It's even possible to turn the handler into a fake method by passing the object ref:

        $obj->autofail([&handler, $obj, $arg1, $arg2]);

    If the reference is to a scalar, the scalar is incremented for each error and execution continues. Switching to a class method example:

        my $rc = 0;
        [do stuff involving Argv objects]
        print "There were $rc failures counted by Argv\n";
  • syfail,qxfail

    Similar to autofail but apply only to system() or qx()/pipe() respectively. Unset by default.

  • lastresults

    Within an autofail handler this may be used to get access to the results of the failed execution. The return code and stdout of the last command will be stored and can be retrieved as follows:

        # set up handler as a fake method (see above)
        $obj->autofail([&handler, $obj, $arg1, $arg2]);
        # then later, in the handler
        my $self = shift;                   # get the obj ref
        my @output = $self->lastresults;    # gives stdout in list context
        my $rc = $self->lastresults;        # and retcode in scalar

    Note that stdout is only available for ->qx, not for ->system. And stderr is never available unless you've explicitly redirected it to stdout. This is just the way Perl I/O works.

  • envp

    Allows a different environment to be provided during execution of the object. This setting is in scope only for the child process and will not affect the environment of the current process. Takes a hashref:

        my %newenv = %ENV;
        $newenv{PATH} .= ':/usr/ucb';
        delete @newenv{qw(TERM LANG LD_LIBRARY_PATH)};

    Subsequent invocations of $obj will add /usr/ucb to PATH and subtract TERM, LANG, and LD_LIBRARY_PATH.

  • autoglob

    If set, the glob() function is applied to the operands ($obj->args) on Windows only. Unset by default.

  • autoquote

    If set, the operands are automatically quoted against shell expansion before system() on Windows and qx() on all platforms (since qx() always invokes a shell and system() always does so on Windows). Set by default.

    An individual word of an argv can opt out of autoquoting by using a leading '^'. For instance:

        ('aa', 'bb', "^I'll do this one myself, thanks!", 'cc')

    The '^' is stripped off and the rest of the string left alone.

  • dbglevel

    Sets the debug level. Level 0 (the default) means no debugging, level 1 prints each command before executing it, and higher levels offer progressively more output. All debug output goes to stderr.

  • dfltsets

    Sets and/or returns the default set of option sets to be used in building up the command line at execution time. The default-default is the anonymous option set. Note: this method takes a hash reference as its optional argument and returns a hash ref as well. The selected sets are represented by the hash keys; the values are meaningless.

  • execwait

    If set, $obj->exec on Windows blocks until the new process is finished for a more consistent UNIX-like behavior than the traditional Win32 Perl port. Perl just uses the Windows exec() routine, which runs the new process in the background. Set by default.

  • inpathnorm

    If set, normalizes pathnames to their native format just before executing. This is NOT set by default, and even when set it's a no-op except on Windows where it converts /x/y/z to \x\y\z. Only the prog and args lists are normalized; options placed in the opts list are left alone.

    However, for better or worse it's common to lump opts and args together so some attempt is made to separate them heuristically. The algorithm is that if the word begins with / we consider that it might be an option and look more carefully: otherwise we switch all slashes to backslashes. If a word is in the form /opt:stuff we assume stuff is meant as a path and convert it. Otherwise words which look like options (start with a slash and contain no other slashes) are left alone.

    This is necessarily an inexact science. In particular there is an ambiguity with combined options, e.g. /E/I/Q. This is a legal pathname and is treated as such. Therefore, do not set combined options as part of the args list when making use of argument path norming. Some Windows commands accept Unix-style options (-x -y) as well which can be useful for disambiguation.

  • outpathnorm

    If set, normalizes pathnames returned by the qx method from \-delimited to /-delimited. This is NOT set by default; even when set it's a no-op except on Windows.

  • noexec

    Analogous to the -n flag to make; prints what would be executed without executing anything.

  • qxargs

    Sets a maximum command line length for each execution, allowing you to blithely invoke $obj->qx on a list of any size without fear of exceeding OS or shell limits. The attribute is set to a per-platform default; this method allows it to be changed as described below.

    A value of 0 turns off the feature; all arguments will be thrown onto one command line and if that's too big it will fail. A positive value specifies the maximum number of arguments to place on each command line. As the number of args has only a tenuous relationship with the length of the command line, this usage is deprecated and retained only for historical reasons (but see below). A negative value sets the overall command line length in bytes, which is a more sensible way to handle it. As a special case, a value of -1 sets the limit to that reported by the system (getconf ARG_MAX on POSIX platforms, 32767 on Windows). The default is -1. Examples:

        $obj->qxargs(0);            # no cmdline length limit
        $obj->qxargs(-2048);        # limit cmdlines to 2048 bytes
        $obj->qxargs(-1);           # limit cmdlines to ARG_MAX bytes
        $obj->qxargs(256);          # limit cmdlines to 256 arguments

    Notes: The actual cmdline length limit is somewhat less than ARG_MAX on POSIX systems for reasons too complex to explain here.

  • syxargs

    Analogous to qxargs but applies to system(). Unlike qxargs, this is turned off by default. The reason is that qx() is typically used to read data whereas system() is more often used to make stateful changes. Consider that "ls foo bar" produces the same result if broken up into "ls foo" and "ls bar" but the same cannot be said for "mv foo bar".

  • stdout

    Setting this attribute to 0, e.g:


    causes STDOUT to be connected to the 1>/dev/null (Unix) or NUL (Windows) device during invocation of the execution methods system, qx, and exec and restored when they finish. Relieves the programmer of the burden and noise of opening, dup-ing, and restoring temporary handles.

    A value of 2 is the equivalent of using 1>&2 to the shell, meaning that it would send stdout to the stderr device.

    It's also possible to pass any non-numeric EXPR; these will be passed to open(). For instance, to accumulate output from the current object in /tmp/foo use:


    Note that in this usage, responsibility for portable constructs such as the existence of /tmp belongs to the programmer.

  • stderr

    As above, for STDERR. A value of 1 is the equivalent of 2>&1, meaning that it sends stderr to the stdout device. E.g.:

        @alloutput = $obj->stderr(1)->qx;
  • stdin

    As above, for STDIN, but note that setting ->stdin to 0 is a no-op. To turn off standard input it's necessary to use a negative value:

  • quiet

    This attribute causes STDOUT to be closed during invocation of the system and exec (but not qx) execution methods. It will cause the application to run more quietly. This takes precedence over a redirection of STDOUT using the <$obj->stdout> method above.

  • attropts

    The above attributes can be set via method calls (e.g. $obj->dbglevel(1)) or environment variables (ARGV_DBGLEVEL=1). Use of the <$obj->attropts> method allows them to be parsed from the command line as well, e.g. myscript -/dbglevel 1. If invoked as a class method it causes options of the same names as the methods above to be parsed (and removed) from the current @ARGV and set as class attributes. As an instance method it parses and potentially depletes the current argument vector of that object, and sets instance attributes only. E.g.:


    would cause the script to parse the following command line:

        script -/noexec 1 -/dbglevel=2 -flag1 -flag2 arg1 arg2 arg3 ...

    so as to remove the -/noexec 1 -/dbglevel 2 and set the two class attrs. The -/ prefix is chosen to prevent conflicts with "real" flags. Abbreviations are allowed as long as they're unique within the set of -/ flags. As an instance method:


    it will parse the current value of $obj->args and run


    for every instance of -/foo=1 found there.


ClearCase::Argv should work on all ClearCase platforms. It's primarily maintained on Solaris 9 and Windows XP with CC 7.0, using Perl5.8.x.


This module is primarily maintained on Solaris 9 and Windows XP using Perl 5.8.x or newer. There is no known reason it should fail to work on any POSIX or Windows (NT4.0 and above) platform with a sufficiently modern Perl.


If you make frequent use of the clone method, you might consider installing the Clone module by Ray Finch. This tends to speed up instance cloning a good bit.


It's not exactly a bug but ... this module served as my laboratory for learning about Perl OO, autoloading, and various other advanced Perl topics. Therefore it was not written in a disciplined manner; rather, I stuck in every neat idea I was playing with at the time. As a result, though it works well as far as I know, there's a hopeless array of ways to do everything. I know the motto of Perl is TMTOWTDI but Argv goes one further: TWTMWTDE (There's Way Too Many Ways To Do Everything).

For instance, to run commands with different values for execution attributes such as autoquote or stderr, you can keep multiple instances around with different attribute sets, or you can keep one template instance which you clone-and-modify before each execution, letting the clone go out of scope immediately:


Or you can keep one instance around and modify its state before each use. Or toggle the class attributes while leaving the instance attributes untouched. Which is better? I don't know the answer, but choosing a consistent style is a good idea.


David Boyce <dsbperl AT>


Copyright (c) 1999-2006 David Boyce. All rights reserved. This Perl program is free software; you may redistribute and/or modify it under the same terms as Perl itself.


Double your money back!


perl(1), Getopt::Long(3), IPC::ChildSafe(3)

For Windows quoting background: