perl

When is the right time (and the wrong time) to use backticks?


Many beginning programmers write code like this:

sub copy_file ($$) {
  my $from = shift;
  my $to = shift;

  `cp $from $to`;
}

Is this bad, and why? Should backticks ever be used? If so, how?


Solution

  • A few people have already mentioned that you should only use backticks when:

    Unfortunately, things like checking the return value properly can be quite challenging. Did it die to a signal? Did it run to completion, but return a funny exit status? The standard ways of trying to interpret $? are just awful.

    I'd recommend using the IPC::System::Simple module's capture() and system() functions rather than backticks. The capture() function works just like backticks, except that:

    The commands also work consistently across operating systems and Perl versions, unlike Perl's built-in system() which may not check for tainted data when called with multiple arguments on older versions of Perl (eg, 5.6.0 with multiple arguments), or which may call the shell anyway under Windows.

    As an example, the following code snippet will save the results of a call to perldoc into a scalar, avoids the shell, and throws an exception if the page cannot be found (since perldoc returns 1).

    #!/usr/bin/perl -w
    use strict;
    use IPC::System::Simple qw(capture);
    
    # Make sure we're called with command-line arguments.
    @ARGV or die "Usage: $0 arguments\n";
    
    my $documentation = capture('perldoc', @ARGV);
    

    IPC::System::Simple is pure Perl, works on 5.6.0 and above, and doesn't have any dependencies that wouldn't normally come with your Perl distribution. (On Windows it depends upon a Win32:: module that comes with both ActiveState and Strawberry Perl).

    Disclaimer: I'm the author of IPC::System::Simple, so I may show some bias.