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.
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.
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";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With