Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I safely pass a filename with spaces to an external command in Perl?

Tags:

escaping

perl

I have a Perl script that processes a bunch of file names, and uses those file names inside backticks. But the file names contain spaces, apostrophes and other funky characters.

I want to be able to escape them properly (i.e. not using a random regex off the top of my head). Is there a CPAN module that correctly escapes strings for use in bash commands? I know I've solved this problem in the past, but I can't find anything on it this time. There seems to be surprisingly little information on it.

like image 938
aidan Avatar asked Aug 12 '09 17:08

aidan


1 Answers

If you can manage it (i.e. if you're invoking some command directly, without any shell scripting or advanced redirection shenanigans), the safest thing to do is to avoid passing data through the shell entirely.

In perl 5.8+:

my @output_lines = do {
    open my $fh, "-|", $command, @args or die "Failed spawning $command: $!";
    <$fh>;
};

If it's necessary to support 5.6:

my @output_lines = do {
    my $pid = open my $fh, "-|";
    die "Couldn't fork: $!" unless defined $pid;
    if (!$pid) {
        exec $command, @args or die "Eek, exec failed: $!";
    } else {
        <$fh>; # This is the value of the C<do>
    }
};

See perldoc perlipc for more information on this kind of business, and see also IPC::Open2 and IPC::Open3.

like image 166
hobbs Avatar answered Sep 29 '22 21:09

hobbs