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

时间:2013-01-14 19:19:17

标签: 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 个答案:

答案 0 :(得分:3)

use strictwarnings pragma中的第一个。您的脚本无法正常工作,因为您没有为$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的新手,你真的真的应该在http://www.onyxneon.com/books/modern_perl/index.html下载现代perl的书,它会每年更新,所以你会发现最新的做法和代码;这肯定胜过任何过时的在线教程。这本书非常好,逻辑结构,使学习perl变得轻而易举。

答案 1 :(得分:2)

$b未定义。

@b$b是不同的变量。一个是列表,另一个是标量。

您正在打印数组的长度,而不是内容。

建议:

  1. 使用“使用警告;”
  2. 使用“use strict;”
  3. 使用“push @a,@ b;”
  4. 你的剧本:

    @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";
    

答案 2 :(得分:0)

$ array返回数组的长度(数组中的元素数) 要将任何元素($ k)推入数组(@arr),请使用push(@arr,$ k)。 在上面的例子中,

使用push(@ b,@ b);