9

Consider this code:

@tmp = split(/\s+/, "apple banana cherry");
$aref = \@tmp;

Besides being inelegant, the above code is fragile. Say I follow it with this line:

@tmp = split(/\s+/, "dumpling eclair fudge");

Now $$aref[1] is "eclair" instead of "banana".

How can I avoid the use of the temp variable?

Conceptually, I'm thinking of something like

$aref = \@{split(/\s+/, "apple banana cherry")};
1
  • 4
    Functions can't return arrays. split returns a list of scalars, just like any sub. Commented Nov 7, 2011 at 5:11

3 Answers 3

19

You could do this if you want an array-ref:

my $aref = [ split(/\s+/, "apple banana cherry") ];
Sign up to request clarification or add additional context in comments.

Comments

3

I figured it out:

$aref = [split(/\s+/, "apple banana cherry")];

Comments

2

While I like mu's answer (and would use that approach first here), keep in mind that variables can be rather easily scoped, even without the use of functions, imagine:

my $aref = do {
  my @temp = split(/\s+/, "apple banana cherry");
  \@temp;
};
print join("-", @$aref), "\n";
# with warnings: Name "main::temp" used only once: possible typo at ...
# with strict: Global symbol "@temp" requires explicit package name at ...
print join("-", @temp), "\n";

Happy coding.

Comments

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.