2013-01-14 31 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);