I have a string of the following format:
word1.word2.word3
What are the ways to extract word2 from that string in perl? I tried the following expression but it assigns 1 to sub:
@perleval $vars{sub} = $vars{string} =~ /.(.*)./; 0@
EDIT:
I have tried several suggestions, but still get the value of 1. I suspect that the entire expression above has a problem in addition to parsing. However, when I do simple assignment, I get the correct result:
@perleval $vars{sub} = $vars{string} ; 0@
assigns word1.word2.word3 to variable sub
.
has a special meaning in regular expressions, so it needs to be escaped..*
could match more than intended. [^.]*
is safer.//
) simply returns true/false in scalar context.You can use any of the following:
$vars{sub} = $vars{string} =~ /\.([^.]*)\./ ? $1 : undef;
$vars{sub} = ( $vars{string} =~ /\.([^.]*)\./ )[0];
( $vars{sub} ) = $vars{string} =~ /\.([^.]*)\./;
The first one allows you to provide a default if there's no match.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With