Chris Oliver Sasota Chris Oliver Sasota - 24 days ago 7
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

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'