Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

$1 - can it be 'reset to null' ?

Status
Not open for further replies.

goliath

MIS
Aug 18, 1999
62
US
Hello,

I'm running some regexp's and I use $1 to get the information within the query but if for example one regexp returns nothing, but the one before it did then $1 still contains the information from the prior success... =(

I tried to do $1 = ""; but that failed with a "read only" error.

Thoughts?
 
Using this approach should solve your problem.
Code:
if ($String =~ /(match1).+(match2)/) {
    $SomeVar = $1;
    $SomeOtherVar = $2;
} else {
    print "No match \n";
}
 
Hmm, I can't quite work it that way becuase it's two different situations for the matching... I'll try to work a variation on that idea somehow...
 
If you match something, won't "" get put into $1 if there's nothing there?

Code:
$var1 = 'hi!!!!';
$var =~ /(!+)/;
# $1 is now "!!!!"
$var =~ /o/;
# Isn't $1 now "" ?
[code]
I assumed it would be.
 
Here's a snippit of my code, maybe you are right, I thought the $1 would revert to null but maybe I'm doing something wrong?

if ($dta =~ /^MAP ROOT/i) {
$dta =~ m/Map Root (.*?):/i;
$drv = $1;
print "$drv,";
print OUT "$drv,";

$dta =~ m/:=(.*?)\\Sys1:/i;
$nsrv = $1;
print "$nsrv,"; print OUT "$nsrv,";
}

In this form it SEEMS that the value of $1 the holds the first iterations value unelss a new one is gotten from the second try.

I'm not a Perl expert so I could be doing any number of things wrong.


Thanks!
 
$1 only gets reset if a match is sucessful. So modifying krel's example

$var1 = 'hi!!!!';
$var =~ /(!+)/;
# $1 is now "!!!!"
$var =~ /i/;
# $1 is now undef

Because the second match is sucessful (it matched the 'i' in 'hi') $1 gets reset to undef.

This is why you should use raider's method of testing the sucess of a match before assigning $1, $2, etc...

jaa
 
Ahh! I'm learning =) I'll convert it to an IF statement, I just couldnt get it to work as in if with ).+(

Thankies!
 
Instead of starting another thread, is there an easy way to see if a line contains two instances of a char?

Thanks
 
Do you mean two instances of ANY char? If so then the following will work.

if ($string =~ /(.).*\1/) {
print "There are 2 $1's in $string\n";
}

If you want a specific char then change the regex to find it.

my $char = 'a'
if ($string =~ /($char).*\1/) {
print "There are 2 $1's in $string\n";
}

jaa
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top