Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl assign regex match to variable with default value

I am familiar with assigning a match to a variable using list context:

my ($ans) = $somevar =~ m/(somestuff)/;

But what if I want to assign a default value to $ans when the match fails? Is there a way to do this well in one expression? Preferably without a conditional operator?

like image 973
NetMage Avatar asked Jan 31 '26 00:01

NetMage


1 Answers

Perhaps the ternary operator will be helpful:

my $ans = $somevar =~ /(somestuff)/ ? $1 : 'default_val';
like image 172
Kenosis Avatar answered Feb 02 '26 14:02

Kenosis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!