Perl `split` does not" split "into the default array

I have this weird problem with split is that it is not a default split into a default array.

Below is the toy code.

 #!/usr/bin/perl $A="A:B:C:D"; split (":",$A); print $_[0]; 

It doesn't print anything. However, if I explicitly broke into a default array, for example

 #!/usr/bin/perl $A="A:B:C:D"; @_=split (":",$A); print $_[0]; 

It prints correctly A. My version of perl is v5.22.1.

+5
source share
2 answers

split by default does not go to @_ . @_ does not work like $_ . This is only for function arguments. perlvar says:

Inside the subroutine, the @_ array contains the parameters passed to this subroutine. Inside the routine, @_ is the default array for pop and shift array operators.

If you run your program using use strict and use warnings , you will see

Useless split in void's context

However, split uses $_ as its second argument (shared string) if nothing is provided. But you should always use the return value for something.

+9
source

You must assign an array partition:

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

Source: https://habr.com/ru/post/1268165/


All Articles