john pfeiffer
  • Home
  • Categories
  • Tags
  • Archives

Perl system commands

perl system commands

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.

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

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

1
2
3
4
#!/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:

1
2
3
4
5
6
7
#!/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.

1
2
3
4
5
#!/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):

1
2
3
4
5
6
7
#!/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:

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

  • « Deploy directories delay function paremeters
  • cherokee drupal 7 migrate »

Published

Oct 5, 2011

Category

bat-vbs-perl

~225 words

Tags

  • bat-vbs-perl 51
  • commands 7
  • perl 14
  • system 9