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

hi, i am working on a problem.I am taking an output of a command and storing it in an array.Now i want the first line of that array.How should i do that?

Replies are listed 'Best First'.
Re: code to get the first line of an array
by davido (Cardinal) on Jul 12, 2005 at 06:47 UTC

    A couple simple ways...

    my $first_line = $array[0]; # or my $first_line = shift @array; # This is destructive to @array.

    See perlintro and shift for details.


    Dave

      ..or
      my ( $first_line ) = @array;

      This works by the fact that the parenthesis denote a list, and you're copying the elements of the array into the elements in the list (of which there is just one in this example). This is non-destructive to the array.

      You can also view the second and third lines and soforth by continuing with this notion:

      my ( $first, $second, $third ) = @array;

      This is a technique I regularly use when parsing parameters passed to a function. The function parameters are placed in @_ and so I write:

      sub myfunction( $ $ $ ) { my ( $param1, $param2, $param3 ) = @_; # ... }
Re: code to get the first line of an array
by anonymized user 468275 (Curate) on Jul 12, 2005 at 07:09 UTC
    Destructive to the array - isn't that a bit of an overstatement? shift does what it says; it shifts the first element of the array out. It therefore "modifies" rather than "destroys".

    One world, one people

      monarch's usage is pretty standard, I think. For example,

      destructive

      (~ function) Capable of modifying its arguments.

      That's from here.

      the lowliest monk

      That statement hit me too. As far as most people are concerned, a destructor should deallocate all the resources an object owns (in a loose sense, not strictly an OO object, here I consider an array as an object).

      shift obviously does not meet that criteria, it is just a usual method.