Chris Oliver Sasota Chris Oliver Sasota - 1 year ago 70
Perl Question

How do I 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

Match the whole string in regex using ^a.* and then replace it using your replacement string.

$str =~ s/^a.*/$replacement/;
print "$str\n"; # would print 'string_begins_with_a'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download