You can extract multiple values from a string using "capturing". The basic version works like this. You capture text in a matched regex by surrounding the text with (...)
. I this example, we'll extract runs of non-whitespace characters either side of ": ".
use feature 'say'; # for "say()"
$_ = 'Invalid version of perl: 5.8.7';
if (/(\S+): (\S+)/) {
say "Language = $1";
say "Version = $2";
}
The captured text is put into variables called $1
and $2
. Notice that we put the whole match in an if
statement to ensure that our regex matches before displaying anything.
An alternative approach which makes your code easier to understand is to copy the matching data into named variables like this:
use feature 'say'; # for "say()"
$_ = 'Invalid version of perl: 5.8.7';
if (my ($language, $version) = /(\S+): (\S+)/) {
say "Language = $language";
say "Version = $version";
}
As others have pointed out, the Perl documentation is well worth reading if you're new to the language. In this case, you should spend an hour or two studying perlretut.