http://qs321.pair.com?node_id=1066106


in reply to Re^2: Assigning Variables to String Elements
in thread Assigning Variables to String Elements

$pi = split('\t', $PAR1_info[0]);

Split returns an array. When you assign an array to a scalar, the array is evaluated in a scalar context and an array evaluated in a scalar context gives the number of elements in the array, not the first element of the array.

There are, as usual with Perl, several ways to get the first element. Here are a couple:

my ($pi) = split(/\t/, $PAR1_info[0]);

my $pi = (split(/\t/, $PAR1_info[0])[0];

Note also that split takes a regular expression (pattern) as its first argument, not a string.

Edit: Some days I should stay away from my keyboard....

As dave_the_m points out, what I said about split returning an array is incorrect. In fact (as is generally the case with functions) what split does depends on the context in which it is evaluated. Split does various things differently when evaluated in scalar context rather than list or void context. Of relevance here, from split:

Splits the string EXPR into a list of strings and returns the list in list context, or the size of the list in scalar context.

And, while split is documented to take a pattern, that pattern can be a string.

Replies are listed 'Best First'.
Re^4: Assigning Variables to String Elements
by dave_the_m (Monsignor) on Dec 07, 2013 at 11:07 UTC
    Split returns an array.
    Strictly speaking, no it doesn't. It returns a list, and in scalar context it is designed to return a list of one element, that element being the number of items that split would have returned in list context. This semantic distinction doesn't make any practical difference for split, but would for something like splice.

    Dave.