Criz Criz - 16 days ago 5
Perl Question

Replace an entire string using regex in Perl

I would like it to look something like this.

my $str = 'axxxx';

my $replacement = 'string_begins_with_a';

$str =~ s/^a/$replacement/;

print "$str\n"; #should print 'string_begins_with_a'

Answer

You just need to consume the rest of the line by adding .* after a:

my $str = 'axxxx';
my $replacement = 'string_begins_with_a';
$str =~ s/^a.*/$replacement/;
print "$str\n"; #prints 'string_begins_with_a'

Or, you may just check if $str starts with a, and then assign the $replacement value to it:

$str = ($str =~ /^a/) ? $replacement : $str;

or just

if ($str =~ /^a/) {
    $str = $replacement;
}
Comments