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!

remembered expression in substitution

Status
Not open for further replies.

jjohnn

Technical User
Feb 11, 2003
43
US
# adds line #'s before every line that
# match the expression at the command line,
# putting parens around the matches
#

$file = 'stam.txt';
open (TEXT, $file);
my $linenum = "000";

while ($line = <TEXT>){
if($line =~/($ARGV[0])/g){
$line =~ s/$1/($ARGV[0])/g;
$linenum++;
print &quot;$linenum &quot;.&quot;$line&quot;;
}
else{
print &quot; $line&quot;;
}
}


In the substitution, I get an error (&quot;use of uninitialized value&quot;)when I try to use $1 in place of $ARGV[0]. I have tried using braces around the &quot;1&quot;, or using &quot;\1&quot; (without the quotes), but I get the same message.
 
try assigning $1 to a temp scalar and then using it?
Code:
if($line =~/($ARGV[0])/g){
  my $tmp = $1;
  $line =~ s/$tmp/($ARGV[0])/g;
...
----------------------------------------------------------------------------------
...but I'm just a C man trying to see the light
 
Thanks. That works as well as simply puting $ARGV[1] in the substitution, but I don't understand why the $1 doesn't work.

Incidentally, it is only the second part of the substitution expression (between the second and third slashes of s///) that complains about $1. $1 can go in the first (search) part of the substituttion expression with no complaints.

puzzling to me.
 
Almost there: there are syntax errors near the &quot;print&quot; and &quot;else&quot; lines; can somebody help me see them?

$file = 'stam.txt';
open (TEXT, $file);
my $linenum = &quot;000&quot;;

while($line=<TEXT>){
$finds =~ s/($ARGV[0])/($1)/g
if ($finds){
$linenum += $finds;
print &quot;$linenum &quot;.&quot;$line&quot;;
}
else{
print &quot; $line&quot;;
}
}
 
The reason [tt]$1[/tt] doesn't work in the second part of the expression is because it is no longer the [tt]$1[/tt] from the initial matching regular expression, but the [tt]$1[/tt] from the match using the left side of the regex. You don't use any grouping, so $1 is undefined.
 
The syntax error is because of a missing semicolon on the line:
[tt]$finds =~ s/($ARGV[0])/($1)/g[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top