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: Regular Expressions:
Using variable $& for getting result

 



FiMko
New User

Jan 11, 2010, 8:47 AM

Post #1 of 3 (2634 views)
Using variable $& for getting result Can't Post

Hi all!

I need your help in very simple problem.

I have a file content like:

Code
string1 
string2
string3


And I have a perl script parsing this file:

Code
if(scalar(@ARGV) == 0) { 
print "None of file paths is specified!";
exit;
}
# for all the specified files
for ($i = 0; $i < @ARGV; $i++) {
$file_path = $ARGV[$i];
open(IN, $file_path) || die; # read next file
while ($line = <IN>) {
$line =~ m/^[^\s].+$/;
print $& . "\n";
}
close (IN);
}


So, I expect the following out:

Code
string1 
string3


But have the following:

Code
string1 
string1
string3


In the second pass the regular expression does not match a text, but variable $& keeps its value from the previous pass ("string1"). This is printed out.

What should I do in such cases? I can't clear variable $& as it is readonly. Could you please give me a hint, I can't find an info in any guide. Thanks in advance!


(This post was edited by FiMko on Jan 11, 2010, 8:50 AM)


toolic
User

Jan 11, 2010, 10:02 AM

Post #2 of 3 (2627 views)
Re: [FiMko] Using variable $& for getting result [In reply to] Can't Post

Print the line only if no leading space is found:


Code
while ($line = <IN>) {  
print $line unless $line =~ m/^\s/;
}



FiMko
New User

Jan 11, 2010, 10:57 AM

Post #3 of 3 (2623 views)
Re: [toolic] Using variable $& for getting result [In reply to] Can't Post

toolic, thanks for help!

Here is one more way to do what I wanted:

Code
if(scalar(@ARGV) == 0) { 
print "None of file paths is specified!";
exit;
}
# for all the specified files
for ($i = 0; $i < @ARGV; $i++) {
$file_path = $ARGV[$i];
open(IN, $file_path) || die; # read next file
while ($line = <IN>) {
if ($line =~ m/^[^\s].+$/) { // operator =~ returns 1 if a match found!
print $& . "\n";
}
}
close (IN);
}


 
 


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

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