CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Intermediate:
$1 becomes undefined after reassignment / substitution

 



Zhris
Enthusiast

Jun 28, 2014, 11:14 PM

Post #1 of 4 (6318 views)
$1 becomes undefined after reassignment / substitution Can't Post

Hey,

I'm getting odd results when working with a re-assigned capture variable. I know of workarounds, but would like to understand the issue. It appears that as soon as I perform a substitution on the new variable, $1 "goes out of scope" (undefined). I've not used warnings in the example below in order not to muddy the output with "use of uninitialized value in concatenation" messages.


Code
my $str = "a  b c   d"; 

while ( $str =~ /(\w\s*)/g )
{
my $char = $1;
$char =~ s/\s+//g;
print ">$char, $1<\n";
}


Output:

Code
>a, < 
>b, <
>c, <
>d, d<


Expected output:

Code
>a, a  < 
>b, b <
>c, c <
>d, d<


Regards,

Chris


(This post was edited by Zhris on Jun 28, 2014, 11:18 PM)


BillKSmith
Veteran

Jun 29, 2014, 3:26 AM

Post #2 of 4 (6309 views)
Re: [Zhris] $1 becomes undefined after reassignment / substitution [In reply to] Can't Post

The document perlvar explains:

Quote

Variables related to regular expressions

Most of the special variables related to regular expressions are side effects. Perl sets these variables when it has a successful match, so you should check the match result before using them.


Any regular expression will change your $1.
Good Luck,
Bill


Laurent_R
Veteran / Moderator

Jun 29, 2014, 7:05 AM

Post #3 of 4 (6237 views)
Re: [BillKSmith] $1 becomes undefined after reassignment / substitution [In reply to] Can't Post


In Reply To
Any regular expression will change your $1.


Well, really, any successful regular expression will change your $1. Which is why Chris got what he expected for the last case (unsuccessful match) but not the three others.


(This post was edited by Laurent_R on Jun 29, 2014, 7:06 AM)


Zhris
Enthusiast

Jun 29, 2014, 10:36 AM

Post #4 of 4 (6091 views)
Re: [BillKSmith] $1 becomes undefined after reassignment / substitution [In reply to] Can't Post

Hey Bill and Laurent,

Thank you for quoting the section of documentation where this is explained.

I had always been under the impression that the $1 .. $n variables retain their value until another regex uses the relevant capture group, regardless of whether a match was successful or not. I guess I have never written code where this has been an issue before i.e. I reassign ASAP and wouldn't normally need to reuse $1 .. $n later on.

Thanks again, this has been a wake up call!

Chris

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives