问题
I would like to use the value of a variable (fixed by a command line option for instance) as a list separator, enabling that value to be a special character (newline, tabulation, etc.).
Unfortunately the naïve approach does not work due to the fact that the two following print statement behave differentely :
my @tab = ("a","b","c");
# block 1 gives expected result:
# a
# b
# c
{
local $" = "\n"; #" let us please the color syntax engine
print "@tab";
}
# block 2 gives unwanted result:
# a\nb\nc
{
use Getopt::Long;
my $s;
GetOptions('separator=s' => \$s);
local $" = "$s"; #" let us please the color syntax engine
print "@tab";
}
Any idea I can correct the block 2 so that I get the wanted result (the one produced by block 1) ?
回答1:
It actually does work the same if you assign the same string. Perl's
"\n"
creates a one character string consisting of a newline. With my shell (bash), you'd use
'
'
to do the same.
$ perl a.pl --separator='
'
a
b
ca
b
c
You didn't do this. You passed a string consisting of the two characters \
and n
to Perl instead.
If you your program to convert two chars \n
into a newline, you'll need to tell it to do so.
my @tab = qw( a b c );
sub handle_escapes {
my ($s) = @_;
$s =~ s/\\([\\a-z])/
$1 eq '\\' ? '\\' :
$1 eq 'n' ? "\n" :
do { warn("Unrecognised escape \\$1"); "\\$1" }
/seg;
return $s;
}
{
my $s = '\n'; #" let us please the color syntax engine
local $" = handle_escapes($s);
print "@tab";
}
{
use Getopt::Long;
my $s;
GetOptions('separator=s' => \$s);
local $" = handle_escapes($s); #" let us please the color syntax engine
print "@tab";
}
$ perl a.pl --separator='\n'
a
b
ca
b
c
来源:https://stackoverflow.com/questions/16556130/perl-how-to-use-command-line-special-characters-newline-tab-in-list-separat