in reply to What's the right way to write a method which returns one line at a time from a file?
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):
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.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; } } ...
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.
|
|---|