Perl/quotemeta

From Wsms

Jump to: navigation, search

quotemeta is a perlfunction that quote metacharacters so that you can use them for things like writing literal shell scripts.

t.pl:

#!/usr/bin/env perl
use warnings;
use strict;

# write the bash commands to move all the .doc files from the current working directory to ~/archives

opendir(CWD, ".") or die "Can't open .: $!";

while ( my $file = readdir CWD ) {
    if ($file =~ /.*\.doc$/){
        my $quoted = quotemeta($file);
        print "mv $quoted /home/ggeller/archives/\n";
        next;
    }
}
closedir(CWD);

Then invoke with something like:

$ ./t.pl > t.bash

t.bash will have something like:

mv George\'s\ Document\.doc /home/ggeller/archives/

Invoke t.bash with something like:

$ . t.bash

The reason for the two step process is so that you can inspect the shell commands before you actually run time. You could do the same commands in your perl script directly, but if you make a mistake, it might be a big one!

see also

Perl Cookbook, p42
$perldoc -f qouotemeta

Personal tools