Tweet

How do I call a system or third party program from perl?

You want to call another program from your perl program.

Solution 1: system call

You can call any program like you would from the command line using a system call. This is only useful if you do not need to capture the output of the program.

    #!/usr/bin/perl
    use strict;
    use warnings;
    my $status = system("vi fred.txt");

Or if you don't want to involve the shell:

    #!/usr/bin/perl
    use strict;
    use warnings;
    my $status = system("vi", "fred.txt");

You'll need to bitshift the return value by 8 (or divide by 256) to get the return value of the program called:

    #!/usr/bin/perl
    use strict;
    use warnings;
    my $status = system("vi", "fred.txt");
    if (($status >>=8) != 0) {
        die "Failed to run vi";
    }

Solution 2: qx call

If you need to capture the output of the program, use qx.

    #!/usr/bin/perl
    use strict;
    use warnings;
    my $info = qx(uptime);
    print "Uptime is: $info\n";

Or if the output has multiple lines (e.g. the output of the "who" command can consist of many lines of data):

    #!/usr/bin/perl
    use strict;
    use warnings;
    my @info = qx(who);
    foreach my $i (@info) {
        print "$i is online\n";
    }

You can also use backticks (`) to achieve the same thing:

    #!/usr/bin/perl
    use strict;
    use warnings;
    my @info = `who`;
    foreach my $i (@info) {
        print "$i is online\n";
    }

See also

Run

    perldoc perlop

and refer to the qx section.

[Top]