Like Perl, how to replace only the first character of a string?

I don't know the slightest amount of Perl and should fix the error in the Perl script.

Given the variable $myvarthat contains the string, if the first character is a period, replace it with "foo / bar".

How can i do this? (Bonus points if you can guess the mistake)

+5
source share
4 answers
$myvar =~ s+^\.+foo/bar+ ;
+9
source

You can use substr :

 substr($myvar, 0, 1, "foo/bar") if "." eq substr($myvar, 0, 1);
+8
source

substr magic:

$_ eq '.' and $_ = "foo/bar" for substr $myvar, 0, 1;

perl 5.12

for(substr($myvar, 0, 1)) {
    when('.') { $_ = "foo/bar" }
}
+5

@eugene, - ActiveState perl 5.10.1 Windows XP. , , .

#!/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";
}

:

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%            --
========================================
+2

All Articles