1

I use quotemeta to escape for file path of Chinese filename. But it returns wrong.

Example of the code:

#!/usr/bin/perl

use Encode;
my $ustring1 = "/opt/游戏美术.txt";
my $ustring2 = quotemeta $ustring1;

print "$ustring1\n" ;
print "$ustring2";
print "\n";

Please help to explain and provide the code to solve this. I'm using Perl v5.10.1 Thanks a lot.

Update question:

#!/usr/bin/perl

use Encode;
use utf8;
use open ':std', ':encoding(UTF-8)';

my $ustring1 = "游戏美术";
my $ustring2 = quotemeta $ustring1;
my $rc = 0xffff & system("echo a > $ustring1.txt2");


print "$ustring1\n" ;
print "$ustring2\n";
print "$rc";
print "\n";

The output is fine now. But the filename of the txt2 file is wrong: 游??美术.txt2. Please help

Diamond
  • 175
  • 1
  • 2
  • 14
  • `quotemeta` is intended to escape characters that are special inside regular expressions. If you want to make a filename safe for interpolation into a shell command, look at the [`String::ShellQuote` module](https://metacpan.org/pod/String::ShellQuote) instead – amon Mar 06 '14 at 07:50

1 Answers1

1

Maybe, use utf 8 helps:

#!/usr/bin/perl

use Encode;
use utf8;
use open ':std', ':encoding(UTF-8)';

my $ustring1 = "/opt/游戏美术.txt";
my $ustring2 = quotemeta $ustring1;

print "$ustring1\n" ;
print "$ustring2";
print "\n";

Output:

/opt/游戏美术.txt
\/opt\/游戏美术\.txt
user4035
  • 22,508
  • 11
  • 59
  • 94
  • 1
    @Diamond Did you save the file in utf8 encoding? It works fine for me, no question marks instead of 戏. Why do you use `quotemeta` function? You don't have any regular expressions. – user4035 Mar 06 '14 at 07:04
  • Does the locale affect here? I am using LANG=en_US.UTF-8. The problem with quotemeta has been solved so please ignore it. Just the filename of txt2 is displayed wrong: my $rc = 0xffff & system("echo a > $ustring1.txt2"); That file is just created by that command, not before – Diamond Mar 06 '14 at 07:09
  • 1
    @Diamond No, I don't think, locale can put "??" instead of the hieroglyph. When you print $ustring1 is it displayed correctly? I use Linux Slackware - maybe your filesystem does this trick? But for me the code works correctly. – user4035 Mar 06 '14 at 07:24
  • Yes, print $ustring1 is fine but not the txt2 filename. I'm using Debian 7. Anyway, Thanks a lot :). The file name is 游\346\217美术.txt2 – Diamond Mar 06 '14 at 07:27