Re: Regex confusion...



On Fri, 28 Sep 2007 00:10:42 +0100, Ben Morrow <ben@xxxxxxxxxxxx> wrote:


Quoth guthrie <guthrie@xxxxxxx>:
sorry for the beginner question, but...

With this code
my $img = "0-12345-abc";
print " Match.1 ", (defined $img);
print " Match.2 ", ($img =~ /\S/);
print " Matched::", $1;

You should never use the $N variables without checking the match
succeeded. In any case, your pattern has no capturing parens, so $1 will
be empty.

Others have already noted that \S and \w only match single characters.

The actual code I'm trying for is:
if(defined $img and $img =~ /\S/) {
if ($img =~ /^(\d)-(\d+)-(\w)$/)
{ my ($t, $zip, $type) = ($1, $2, $3); }

This can be simplified to

if (
my ($t, $zip, $type) =
$img =~ /^(\d)-(\d+)-(\w+)$/
) {

which avoids the need to use the $N variables altogether.

Ben

It might be quicker to check for sucess first then do the asignment

$_ = "......";
if ( /^(\d)-(\d+)-(\w+)$/ )
{
#use $1,2,3 or asign
($t, $zip, $type) = ($1, $2, $3);
}


.