Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

split

perl

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.

like image 420
drcyber Avatar asked May 24 '17 08:05

drcyber


2 Answers

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.

like image 63
simbabque Avatar answered Nov 11 '22 20:11

simbabque


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";
like image 45
Gerhard Avatar answered Nov 11 '22 21:11

Gerhard