Criz Criz - 1 year ago 84
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 Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download