2

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'

2 Answers 2

2

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks this answer is useful too!
Sorry my bad, I was not aware that you posted yours half a minute earlier.
1

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

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

2 Comments

Thanks this what I was looking for!
I do not say you copied from my answer, but that it contains just the same solution. I know that SO has some lags displaying answers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.