In Perl, how can I replace only the first character of a string?
I don't know the slightest bit of Perl and have to fix a bug in a Perl script.
Given a variable $myvar
which contains a string, if the first character is a dot, replace it with "开发者_Python百科foo/bar".
How can I do this?
(Bonus points if you can guess the bug)$myvar =~ s+^\.+foo/bar+ ;
You can use substr:
substr($myvar, 0, 1, "foo/bar") if "." eq substr($myvar, 0, 1);
Some substr
magic:
$_ eq '.' and $_ = "foo/bar" for substr $myvar, 0, 1;
And this syntax makes me love perl 5.12
for(substr($myvar, 0, 1)) {
when('.') { $_ = "foo/bar" }
}
Inspired by the discussion on @eugene's answer, here are some micro-benchmarks using ActiveState perl 5.10.1 on Windows XP. Of course, my benchmarks suck, so take it with a spoonful of salt.
#!/usr/bin/perl
use strict; use warnings;
use Benchmark qw( cmpthese );
my $x = 'x' x 100;
my $y = '.' . $x;
for my $s ($x, $y) {
printf "%33.33s ...\n\n", $s;
cmpthese -5, {
's///' => sub {
my $z = $s;
$z =~ s{^\.}{foo/bar};
},
'index/substr' => sub {
my $z = $s;
if (0 == index $z, '.') {
substr($z, 0, 1, 'foo/bar');
}
},
'substr/substr' => sub {
my $z = $s;
if ('.' eq substr $z, 0, 1) {
substr($z, 0, 1, 'foo/bar');
}
},
};
print '=' x 40, "\n";
}
Output:
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ... Rate index/substr substr/substr s/// index/substr 1622404/s -- -14% -42% substr/substr 1890621/s 17% -- -32% s/// 2798715/s 73% 48% -- ======================================== .xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ... Rate s/// substr/substr index/substr s/// 367767/s -- -57% -62% substr/substr 857083/s 133% -- -10% index/substr 956428/s 160% 12% -- ========================================
精彩评论