PerlMe has asked for the wisdom of the Perl Monks concerning the following question:

Hi,
I am trying to convert a shell scrpt to perl script.
Sheel script:
MSG = `tail -n 10 $ERRLOG`

The output of the tail command will be in the string variable MSG;
How can I do it in perl
Perl Script:
system "tail -n 10 $ERRLOG";
I would be using the above call but how to grab the result in to a string variable?
Thanks, R

Replies are listed 'Best First'.
Re: system call: Unix system call result into a variable
by GrandFather (Saint) on Jul 17, 2007 at 22:06 UTC

    Try:

    my $MSG = `tail -n 10 $ERRLOG`;

    but really you ought to consider using something like File::Tail to do the job instead.


    DWIM is Perl's answer to Gödel
      File::Tail is more for "tail -f" functionality, where you want to keep reading from a continuously updated (i.e. appended to) file. Using backticks (as in your example) or qx is a perfectly acceptable (and simple, efficient) solution.
        File::Tail may be used like a conventional tail(1) - without the rescan - by specifying the 'tail' argument to the constructor. However to prevent the 'wait' you have to only display those lines you ask for (then destroy the object). For example:
        use strict; use File::Tail; my $num_of_lines = 10; my $tail = new File::Tail (name=>$ERRLOG, tail => $num_of_lines); for (1..$num_of_lines) { my $line = $tail->read(); print "$_: $line"; } $tail = undef;

        update: I emailed the author of File::Tail (Matija Grabnar) with this solution, and he was kind enough to respond immediately with the following:
        "You're wasting most of File::Tails potential, but yes, that should work.
        Note that it won't work if your input is a stream or a pipe (for which ordinary tail would work)."
Re: system call: Unix system call result into a variable
by j1n3l0 (Friar) on Jul 17, 2007 at 22:08 UTC
    You can use the back ticks or qx() like so:

    $error_string = qx(tail -n 10 $ERRLOG);
    You can also get your result in an array:

    @error_array = qx(tail -n 10 $ERRLOG);
    Hope that helps ;)

    UPDATE: Removed the double-quotes. Thanks quester
      Although without the extra quotes, since qx() itself is one of the "quote-like operators" described in perlop:
      @error_array = qx(tail -n 10 $ERRLOG);
Re: system call: Unix system call result into a variable
by mjscott2702 (Pilgrim) on Jul 18, 2007 at 01:05 UTC
    You can also use the open function to run the command and create a filehandle for the pipe:
    open($cmd, "tail -n 10 $ERRLOG |"); while(<$cmd>) { # do something here }
    This may be more generic, if you want to do some more complicated processing of each line of output from the system call?