Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: Line number in a file

by edan (Curate)
on Jul 06, 2004 at 09:58 UTC ( [id://372055]=note: print w/replies, xml ) Need Help??


in reply to Line number in a file

I think the others have answered your question about how to get the line number in the file-reading loop using $.. But your question also seems to be "How do I save off the value for later use?" Maybe I'm misunderstanding the question, or maybe my answer is blindingly obvious to you once you know about $., but here is an example (using your own example code) of how you might save off that info for later use when you process the data you collected:

while (<MYFILE>) { $alldata .= $_ ; if(/(\S+)\s+(\d+)/) { $mylist{$1} = {value => $2, linenum => $. }; } }

You see that instead of just saving off the right-hand value ($2) as a scalar value in the (badly-named) hash %mylist, the value is a hash-reference which contains the value and the line-number it was found on. You would then access the values along the lines of:

for my $key ( keys %mylist ) { my $value = $mylist{$key}{value}; my $linenum = $mylist{$key}{linenum}; print "$key has value $value, found on line $linenum\n"; }

HTH

--
edan

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://372055]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (2)
As of 2024-04-26 00:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found