Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl context - why is return value not the same as $1?

Tags:

regex

perl

I found that in some situations that the return value from a regex match is True and other times the return value in the ()

eg, I am finding all text up to a semi-colon:

my $blop = "some;different;fields";
if(some expression)
{
    my $blip = $blop =~ /([^;]+)/;
}

I expected $blip eq "some", but it is 1 (or TRUE) return value from the check.

$1 contains my desired result, so I can write:

$blop =~ /([^;]+)/;
my $blip = $1;

But that's inefficient. I am sure that in other scenarios that the return is the bracketed result, what is different here?

like image 851
user226035 Avatar asked Dec 21 '25 02:12

user226035


1 Answers

If you give the regex list context, it returns the captures in the list:

use strict;
use warnings;

my $blop = "some;different;fields";
my($blip) = $blop =~ /([^;]+)/;

print "$blip\n";
print "$1\n";

That prints 'some' twice.

In a scalar context, a regex returns true if it matched and false otherwise (which is why you can use them in conditions). Add these two lines to the code above:

my $blup = $blop =~ /([^;]+);([^;]+)/;
print "$blup : $1 : $2\n";

and the extra code prints:

1 : some : different
like image 138
Jonathan Leffler Avatar answered Dec 22 '25 19:12

Jonathan Leffler



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!