drcyber
drcyber

Reputation: 151

Perl `split` does not `split` to default array

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.

Upvotes: 6

Views: 686

Answers (2)

user7818749
user7818749

Reputation:

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";

Upvotes: 5

simbabque
simbabque

Reputation: 54323

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.

Upvotes: 10

Related Questions