-1

我的程序是

#!\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, 123or 5, 5, 123。为什么会有这样的行为?为什么我没有得到输出1 2 3 homer marge lisa maria

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

4

3 回答 3

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 变得轻而易举。

于 2013-01-14T19:36:25.557 回答
2

$b未定义。

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

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

建议:

  1. 使用“使用警告;”
  2. 使用“使用严格;”
  3. 使用“推@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";
于 2013-01-14T19:23:31.620 回答
0

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

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

于 2013-01-14T19:27:47.960 回答