On Jul 19, 2012, at 5:10 PM, Sheppy R wrote:
> I'm wondering what is the least resource intensive way to read just one
> item of a file. I'm looking at one of two options (I'm assuming there are
> more that I'm just not familiar with). The first idea is to run grep
> through a system command. The second is to open the file for reading then
> scan each line for the matching text.
>
> my $thing = `grep "text" file`;
>
> my $file = 'file';
> my $FH;
> open($FH, '<', $file);
> for <FH>
> {
> if m/(thing)/
> { $thing = $1 }};
>
> I know its basic code with a lot of stuff missing, but I think you get the
> idea. Is there another method that might be even cheaper than these two?
Opening and reading the file from within your program will be more efficient
than forking a child process to run grep and return its output. Creating a
process has some overhead, and grep will still have to open and read the entire
file.
You can make your program even more efficient if you stop reading the file once
you have found your item.
However, unless you have very large files, the difference in efficiency in any
of these approaches is likely to be negligible from a practical standpoint.
When in doubt, benchmark!
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/