N
niall.macpherson
I know this should be a fairly simple question but I have been
searching for a while and can't find an obvious answer.
When testing a pattern , I tended to use the method shown in METHOD 1
in the code below., i.e use the temporary variables $1, $2, $3 etc.
METHOD 2 seems to be better from my point of view as it avoids the
code being littered with lots of $1, $2, $3 ... variables . However
the multiple defined() calls make it look a bit unwieldy.
Am I missing an obviously more elegant way of checking that all three
values have been captured ? I do not want to put the results in an
array as I need the variable names to be meaningful to other people
(although obviusly a hash may be possible).
I am only interested in a full match , i.e all 3 (or however many)
values captured .
use strict;
use warnings;
my $teststr = '123 456 abcd';
my ($var1, $var2, $var3);
### METHOD 1
if($teststr =~ m/(\d+)\s+(\d+)\s+(\w*)/)
{
($var1, $var2, $var3) = ($1, $2, $3);
print STDERR "\nMETHOD 1" , ' var1 = ' , $var1 , ' var2 = ' , $var2 ,
' var3 = ' , $var3, "\n";
}
else
{
print STDERR "\nMETHOD 1 No Match\n"
}
### METHOD 2
($var1, $var2, $var3) = $teststr =~ m/(\d+)\s+(\d+)\s+(\w*)/;
if(defined($var1) && defined($var2) && defined($var3))
{
print STDERR "\nMETHOD 2" , ' var1 = ' , $var1 , ' var2 = ' , $var2 ,
' var3 = ' , $var3, "\n";
}
else
{
print STDERR "\nMETHOD 2 No Match\n"
}
searching for a while and can't find an obvious answer.
When testing a pattern , I tended to use the method shown in METHOD 1
in the code below., i.e use the temporary variables $1, $2, $3 etc.
METHOD 2 seems to be better from my point of view as it avoids the
code being littered with lots of $1, $2, $3 ... variables . However
the multiple defined() calls make it look a bit unwieldy.
Am I missing an obviously more elegant way of checking that all three
values have been captured ? I do not want to put the results in an
array as I need the variable names to be meaningful to other people
(although obviusly a hash may be possible).
I am only interested in a full match , i.e all 3 (or however many)
values captured .
use strict;
use warnings;
my $teststr = '123 456 abcd';
my ($var1, $var2, $var3);
### METHOD 1
if($teststr =~ m/(\d+)\s+(\d+)\s+(\w*)/)
{
($var1, $var2, $var3) = ($1, $2, $3);
print STDERR "\nMETHOD 1" , ' var1 = ' , $var1 , ' var2 = ' , $var2 ,
' var3 = ' , $var3, "\n";
}
else
{
print STDERR "\nMETHOD 1 No Match\n"
}
### METHOD 2
($var1, $var2, $var3) = $teststr =~ m/(\d+)\s+(\d+)\s+(\w*)/;
if(defined($var1) && defined($var2) && defined($var3))
{
print STDERR "\nMETHOD 2" , ' var1 = ' , $var1 , ' var2 = ' , $var2 ,
' var3 = ' , $var3, "\n";
}
else
{
print STDERR "\nMETHOD 2 No Match\n"
}