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

Re: Slicing the output of a command

by TomDLux (Vicar)
on Jul 10, 2015 at 02:42 UTC ( [id://1134073]=note: print w/replies, xml ) Need Help??


in reply to Slicing the output of a command

Every once in a while, there is some activity which is relatively simple to perform using a shell command, but would be somewhat inconvenient using Perl commands. The down side is that it's generally sloppy.

If you're going to get the contents of a file, and you're dealing with a very short throw-away script, it might make sense to `cat` it.

But you're launching a shell (many milliseconds), opening the file (some milliseconds), loading all it's contents into memory, outputting the contents from the sub-process to the Perl script. If you open a file in Perl, it takes the same amount of time as when you do it in a sub-shell, even though you have to open() the file, <read> the contents, just no sub-shell.

Just about anything you want to do, is available internally in Perl, either built-in, provided by a core module, or availaable as an add-on module. Go to Cpan.org or metacpan.org or search for what you need. For example, gzip-ing or gunzip-ing a file is as simple as use-ing the module, and specifying something in the open() command.

As Occam said: Entia non sunt multiplicanda praeter necessitatem.

Replies are listed 'Best First'.
Re^2: Slicing the output of a command
by marioroy (Prior) on Jul 10, 2015 at 03:13 UTC

    That is beautiful TomDLux. Thus, a demonstration for the OP.

    my @foo = `cat very_large_file | head -4`;

      Why cat the whole file just to discard all but the first four lines:

      my @foo = `head -4 very_large_file`;

      With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.
      I'm with torvalds on this Agile (and TDD) debunked I told'em LLVM was the way to go. But did they listen!

        +1 BrowserUk. I'm not sure if the behavior is the same in Windows, but the 'cat command' receives a PIPE signal and exits once count lines have been read by the 'head command'.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (1)
As of 2024-04-16 16:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found