0

I have the following code:

#!/usr/bin/perl

use strict;
use feature qw(say);

my $raw_text = "a b c d e f g h";

my @array = split(/ /, $raw_text);
my $element = @array[0];

say "Element [0] of array is : ", $array[0];

This prints on STDOUT:

Element [0] of array is : a

So far, so good. However if I want to retrieve the element straightforward from the split method, I would think of:

my $element = split(/ /, $raw_text)[0];

But it turns out that this throws a compilation error. Doing some research I figured out that I have to type:

my $element = ( split(/ /, $raw_text) )[0];

The question is: Why are the extra parenthesis necessary?

I might be missunderstanding the parenthesis meaning for this case.

1 Answer 1

3

The syntax error is to force you to disambiguate the expression, which could be interpreted as either

split((/ /, $raw_text)[0])

or

(split(/ /, $raw_text))[0]

In general, Perl will make a "best guess" at the intention of ambiguous code, but in this case the designers decided that there was no real way to decide on a "most likely" interpretation, and so caused the construct to fail in compilation to force the author to disambiguate the code

Note that the inner parentheses are superfluous, and the expression may be written like so

(split / /, $raw_text)[0]
Sign up to request clarification or add additional context in comments.

1 Comment

I would have never thought of writing the expression as (split / /, $raw_text)[0]. Certainly, it makes much more sense now. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.