Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: What's the right way to write a method which returns one line at a time from a file?

by perl-diddler (Chaplain)
on Nov 22, 2020 at 13:22 UTC ( [id://11124020]=note: print w/replies, xml ) Need Help??


in reply to What's the right way to write a method which returns one line at a time from a file?

What type of algorithm you use depends on what type of interface you want to work with.

I.e. instead of returning a file handle, you might just want your reader routine to return the I/O. I wanted to run a command and read the output line at a time as if I ran the command on the command line and piped it into my perl-script. So I wrote a module called 'Cmd' that I can pass what I want 'run' as a param, and keep calling it with the same command until it returns "undef", like (note: the below was typed in 'raw', and not tested):

use Cmd; use P; use Cmds qw(ip); # command finder that produces '$Ip' with abspath of +'ip' my @cmd = qw( $Ip addr list ); local $_; my %intf2addrs; my $intf; while ($_=Cmd->run(\@cmd)) { if (/^(\S+):/) { $intf=$1;next; } if (/^\s+inet\s([^\s]+)\s/) { next unless $intf; $int2addrs{$intf}=$1; P "intf %10s: %s", $intf, $1; } } ...
The routine stored the cmdline as a hash key to the needed info to the commands output. It ran commands and stored the output for subsequent calls with the same params and returned undef when done.

So -- how you want to do what you are doing, depends on what type of interface you want to use. At the time, I wanted something that conceptually was similar to me invoking the command on the command line and piping its output into my perl program -- except the invoking of the command was in perl.

As is oft said of perl, there are many ways to solve a problem in perl.

  • Comment on Re: What's the right way to write a method which returns one line at a time from a file?
  • Download Code

Log In?
Username:
Password:

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

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

    No recent polls found