6

I have this strange problem with split in that it does not by default split into the default array.

Below is some toy code.

#!/usr/bin/perl

$A="A:B:C:D";
split (":",$A);
print $_[0];

This does not print anything. However if I explicitly split into the default array like

#!/usr/bin/perl

$A="A:B:C:D";
@_=split (":",$A);
print $_[0];

It's correctly prints A. My perl version is v5.22.1.

2
  • 3
    @_ is not "the default array". @_ is the array that contains parameters to a subroutine. There is nothing in the Perl documentation that calls it the default array. Commented May 24, 2017 at 9:04
  • 1
    @DaveCross that's not entirely correct. perldoc.perl.org/perlvar.html#%40ARG says Inside a subroutine, @ is the default array for the array operators pop and shift_. But you are right of course. Commented May 24, 2017 at 9:11

2 Answers 2

10

split does not go to @_ by default. @_ does not work like $_. It's only for arguments to a function. perlvar says:

Within a subroutine the array @_ contains the parameters passed to that subroutine. Inside a subroutine, @_ is the default array for the array operators pop and shift.

If you run your program with use strict and use warnings you'll see

Useless use of split in void context at

However, split does use $_ as its second argument (the string that is split up) if nothing is supplied. But you must always use the return value for something.

Sign up to request clarification or add additional context in comments.

4 Comments

split in void context used to populate @_
@ikegami when was that?
Gone in 5.12. Deprecated at least as early as 5.8.8
@ikegami thanks for looking that up. I think we can leave that as a comment. OP is aking for 5.22. If you feel it should go into the answer, feel free to edit it in though.
5

You have to assign the split to an array:

use strict;
use warnings;

my $string = "A:B:C:D";
my @array = split(/:/, $string);
print $array[0] . "\n";

1 Comment

And don't call your variables $a @a - it's bad to use single letter names anyway, but especially when it is $a or $b which are used by sort

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.