in reply to Re: perl pattern match for end of string using STDIN and chomp
in thread perl pattern match for end of string using STDIN and chomp

This "previous value of $1" can be problematic. One of the practices that I often use in my code is to NOT use $1 or $2, etc. I like to assign $1 right away to a variable that has more contextual meaning (like $name, $cust_id) or whatever. Why have $name = $1;?

One way to do this is illustrated below, put the match into a list context and use list slice to get $1,$2, etc. If "$1" is undef, then in this case $thing gets undef, not the previous value of $1.

print "match failed\n" unless $string =~ m/(.+)\.BBB$/; print "dollar $1:\n"; #prints previous $1 value my ($thing) = ($string =~ m/(.+)\.BBB$/)[0]; print "thing =$thing\n"; #$thing is undef