使用 unshift 分配给变量的问题
Problem using unshift to assign to a variable
我尝试split
一个字符串并分配一个数组,然后在开始使用unshift
添加http。
但是,我没有得到想要的输出。我在这里做错了什么?
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";
输出是:
checking the split function:
script.spoken-tutorial.org index.php Perl
printing new array: 4
为什么不添加 http 而是给出数字 4(数组长度)?
这是记录在案的行为。来自 perldoc -f unshift:
unshift ARRAY,LIST
Does the opposite of a shift. Or the opposite of a push, depending on how you look at it. Prepends list to the front of the array and
returns the new number of elements in the array.
请参阅加粗的最后一部分。这意味着函数 unshift()
的 return 值是数组的大小。这就是你所做的。
unshift(@arr, 'http://'); # this returns 4
你想做的是
my @newarr = ('http://', @arr);
或
my @newarr = @arr;
unshift @newarr, 'http://';
我尝试split
一个字符串并分配一个数组,然后在开始使用unshift
添加http。
但是,我没有得到想要的输出。我在这里做错了什么?
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";
输出是:
checking the split function:
script.spoken-tutorial.org index.php Perl
printing new array: 4
为什么不添加 http 而是给出数字 4(数组长度)?
这是记录在案的行为。来自 perldoc -f unshift:
unshift ARRAY,LIST
Does the opposite of a shift. Or the opposite of a push, depending on how you look at it. Prepends list to the front of the array and returns the new number of elements in the array.
请参阅加粗的最后一部分。这意味着函数 unshift()
的 return 值是数组的大小。这就是你所做的。
unshift(@arr, 'http://'); # this returns 4
你想做的是
my @newarr = ('http://', @arr);
或
my @newarr = @arr;
unshift @newarr, 'http://';