2013-01-14 33 views
-1

我的计划是perl中的push函数不向现有数组添加元素。为什么?

#!\usr\bin\perl 

@a = (1,2,3); 
@b= ("homer", "marge", "lisa", "maria"); 
@c= qw(one two three); 

print push @a, $b; 
print "\n"; 

@count_number= push @a, $b; 

print @count_number; 
print "\n"; 
print @a; 

我得到输出

4 
5 
123 

为什么会收到输出4, 5, 123?为什么我的数组不能扩展?此外,输出不是4, 4, 1235, 5, 123。为什么这样的行为为什么我没有得到输出1 2 3 homer marge lisa maria

我是初学者。谢谢你的时间。

回答

3

第一个use strictwarningspragma。你的脚本不起作用,因为你没有为$b变量分配任何东西,所以你正在向数组推送空值,并且正如你刚刚在数组中打印元素的数量那样。如果我没有记错的话,push元素只会在新元素被推入数组之后返回数组的数量,所以返回应该总是一个标量。

my @a = (1,2,3); 
my @b= ("homer", "marge", "lisa", "maria"); 
my @c= qw(one two three); 

#merge the two arrays and count elements 
my $no_of_elements = push @a, @b; 
print $no_of_elements; 

#look into say function, it prints the newline automatically 
print "\n"; 

#use scalar variable to store a single value not an array 
my $count_number= push @a, $b; 

print @count_number; print "\n"; 

print @a; 

而且有趣的事实,如果你print @array它会列出不带空格的所有元素,但如果你用双引号括阵列,print "@array",就会把空间中的元素之间。 哦,最后但并非最不重要的一点,如果你是perl的新手,你真的真的重新下载现代perl的书,在http://www.onyxneon.com/books/modern_perl/index.html,这是每年更新,所以你会发现那里最新的做法和代码;这肯定会击败任何过时的在线教程。此外,这本书是非常好的,逻辑结构,使学习Perl变得轻而易举。

+2

'strict'不会捕获错误的$ b变量,因为'$ b'是'sort'使用的预定义变量。尽管如此,warnings会将其作为未定义的值在print中捕获。 – TLP

+0

你是对的,不知道我错过了什么...... –

2

$b未定义。

@b$b是不同的变量。一个是列表,另一个是标量。您正在打印数组的长度,而不是内容。

建议:

  1. 使用 “使用警告;”
  2. 使用“严格使用”
  3. 使用“push @a,@b;”

你的脚本:

@a = (1,2,3); # @a contains three elements 
@b= ("homer", "marge", "lisa", "maria"); # @b contains 4 elements 
@c= qw(one two three); # @c contains 3 elements 
print push @a, $b;  # $b is undefined, @a now contains four elements 
         #(forth one is 'undef'), you print out "4" 
print "\n"; 

@count_number= push @a, $b; # @a now contains 5 elements, last two are undef, 
          # @count_number contains one elements: the number 5 

print @count_number;  # you print the contents of @count_number which is 5 
print "\n"; 
print @a;     # you print @a which looks like what you started with 
          # but actually contains 2 undefs at the end 

尝试这种情况:

#!/usr/bin/perl 
use warnings; 
use strict; 

my $b = 4; 
my @a = (1,2,3); 
my @b= ("homer", "marge", "lisa", "maria"); 
my @c= qw(one two three); 

print "a contains " . @a . " elements: @a\n"; 

push @a, $b; 
print "now a contains " . @a . " elements: @a\n"; 

my $count_number = push @a, $b; 
print "finally, we have $count_number elements \n"; 
print "a contains @a\n"; 
0

$阵列返回数组的长度(元素的数量阵列中) 为了将任何元件($ķ )插入数组(@arr),使用push(@arr,$ k)。在上述情况下,

使用推送(@b,@b);