NAME

System::Sub - Wrap external command with a DWIM sub

VERSION

version 0.162800

SYNOPSIS

    use System::Sub 'hostname';  # Just an example (use Sys::Hostname instead)

    # Scalar context : returns the first line of the output, without the
    # line separator
    my $hostname = hostname;

    # List context : returns a list of lines without their line separator
    use System::Sub 'ls';
    my @files = ls '-a';

    # Process line by line
    ls -a => sub {
        push @files, $_[0];
    };

    use System::Sub 'df' => [ '@ARGV' => [ '-P' ] ]; # -P for POSIX
    df => sub {
        return if $. == 1; # Skip the header line
        # Show the 6th and 5th columns
        printf "%s: %s\n", (split / +/, $_[0])[5, 4];
    };

    # Import with options
    use System::Sub ssh => [ '$0' => '/usr/bin/ssh',
                             '@ARGV' => [ qw< -o RequestTTY=no > ] ];

    # Handle exit codes
    use System::Sub 'zenity'; # a GTK+ dialog display
    eval {
        zenity --question
            => --text => 'How are you today?'
            => --ok-label => 'Fine!'
            => --cancel-label => 'Tired.'
    };
    given ($? >> 8) {
        when (0) {
        }
        when (1) {
        }
    }

    # Import with a prototype (see perlsub)
    use System::Sub 'hostname()';  # Empty prototype: no args allowed
    use System::Sub hostname => [ '()' => '' ];  # Alternate syntax
    use strict;
    # This will fail at compile time with "Too many arguments"
    hostname("xx");

DESCRIPTION

See also System::Sub::AutoLoad for even simpler usage.

System::Sub provides in your package a sub that wraps the call to an external program. The return value is line(s) dependending on context (wantarray).

This may be what you need if you want to run external commands as easily as from a Unix shell script but with a perl-ish feel (contextual output). So this is not a universal module for running external programs (like IPC::Run) but instead a simpler interface for a common style of external programs.

System::Sub may be useful if:

  • you want to run the command synchronously (like system or backquotes)

  • the command

    - is non-interactive (all the input is fed at start)
    - input is @ARGV and STDIN
    - output is STDOUT
    - the exit code is what matters for errors
    - STDERR will not be captured, and will go to STDERR of your program.

The underlying implementation is currently IPC::Run, but there is no garantee that this will stay that way. IPC::Run works well enough on both Unix and Win32, but it has its own bugs and is very slow.

IMPORT OPTIONS

Options can be set for the sub by passing an ARRAY just after the sub name on the use System::Sub line.

The sigil ($, @, %) is optional.

  • (): prototype of the sub. See "Prototypes" in perlsub.

  • $0: the path to the executable file. It will be expanded from PATH if it doesn't contain a directory separator.

  • @ARGV: command arguments that will be inserted before the arguments given to the sub. This is useful if the command always require a basic set of arguments.

  • %ENV: environment variables to set for the command.

  • >: I/O layers for the data fed to the command.

  • <: I/O layers for the data read from the command output.

  • &?: sub that will be called if ($? >> 8) != 0.

        sub {
            my $name = shift; # name of the sub
            my $code = shift; # exit code ($?)
            my $cmd = shift;  # array ref to the executed command
    
            # Default implementation:
            require Carp;
            Carp::croak("$name error ".($code >> 8));
        }

    Mnemonic: & is the sigil for subs and $? is the exit code of the last command.

SUB USAGE

Arguments

The scalar arguments of the sub are directly passed as arguments of the command.

The queue of the arguments may contain values of the following type (see "ref" in perlfunc):

  • CODE

    A sub that will be called for each line of the output. The argument is the chomp-ed line.

        sub {
            my ($line) = @_;
        }

    This argument must always be the last one.

  • REF

    A reference to a scalar containing the full input of the command.

  • ARRAY

    A reference to an array containing the lines of the input of the command. \n will be appended at the end of each line.

Return value(s)

  • Scalar context

    Returns just the first line (based on $/), chomped or undef if no output.

  • List context

    Returns a list of the lines of the output, based $/. The end-of-line chars ($/ are not in the output.

  • Void context

    If you do not specify a callback, the behavior is currently unspecified (suggestions welcome).

SEE ALSO

TRIVIA

I dreamed about such a facility for a long time. I even worked for two years on a ksh framework that I created from scratch just because at the start of the project I didn't dare to bet on Perl because of the lack of readability of the code when most of the work is running other programs.

After that project I never really had the need to run the same command in many places of the code, and in many different ways. Until I had the need to wrap Git in the release script of my github-keygen project. I wrote the first version of the wrapper there, and quickly extracted it as this module. So, here is it!

Last but not least, the pun in the package name is intended.

AUTHOR

Olivier Mengué, dolmen@cpan.org.

CONTRIBUTORS

Philippe Bruhat (BOOK).

See the Git log for details.

COPYRIGHT & LICENSE

Copyright © 2012 Olivier Mengué.

This library is free software; you can redistribute it and/or modify it under the same terms as Perl 5 itself.