Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: reading the file using the line number

by padma (Initiate)
on Dec 01, 2006 at 12:09 UTC ( [id://587173]=note: print w/replies, xml ) Need Help??


in reply to reading the file using the line number

You can use the following sub routine to extract particular lines from a file :
sub extract { my ($filename, $line_no)=@_; my $line; open (FILE, $filename) || die "$filename can't be opened $! " if ($line_no =~ /\D/) { while ($line=<FILE>) { if ($line =~ /$line_no/) { return $line; } } } else { foreach (1..$line_no) { $line = <FILE>; } return $line; } }
You have to pass the filename and the line number required. You can pass only one line no. required at a time. This can also be used to obtain a phrase from the file by passing the phrase to the sub routine.
An example: $file = "example.txt"; $line_no_reqd = 4; $result = &imp($file,$line_no_reqd); print $result;
This example will fetch the contents in line no. 4 from the file, example.txt and print it.

Replies are listed 'Best First'.
Re^2: reading the file using the line number
by Fengor (Pilgrim) on Dec 01, 2006 at 12:22 UTC
    sub extract { (my $filename, my $line_no)=@_; open (FILE, $filename) or die "$filename can't be opened: $! "; my $line = <FILE>; $. = $line_no; $line = <FILE> or die "Couldn't read line $line_no: $!"; return $line; }

    --
    "WHAT CAN THE HARVEST HOPE FOR IF NOT THE CARE OF THE REAPER MAN"
    -- Terry Pratchett, "Reaper Man"

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (4)
As of 2024-04-25 22:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found