1

I tried to split one string and assign an array, and then add http at the start using unshift. But, I am not getting the desired output. What am I doing wrong here?

use strict;
my $str = 'script.spoken-tutorial.org/index.php/Perl';
my @arr = split (/\//,$str);
print "chekcing the split function:\n @arr\n";
my @newarr = unshift(@arr, 'http://');
print "printing new array: @newarr\n";

the output is:

checking the split function:
 script.spoken-tutorial.org index.php Perl
printing new array: 4

Why instead of adding http is it giving number 4 (which is array length)?

4

1 回答 1

3

这是记录在案的行为。从perldoc -f unshift

取消移位数组,列表

做相反的转变。或者与推动相反,这取决于您如何看待它。将列表添加到数组的前面并 返回数组中的新元素数

见加粗的最后一部分。这意味着函数的返回值unshift()是数组的大小。这就是你所做的。

unshift(@arr, 'http://');   # this returns 4

你想要做的是

my @newarr = ('http://', @arr);

或者

my @newarr = @arr;
unshift @newarr, 'http://';
于 2021-05-08T07:04:40.887 回答