2013-03-19 55 views
1

下面的腳本是在學習Perl的鍛鍊4.6.4。要求在不使用reverse的情況下打印出「反向列表」。爲什麼會出現「未初始化值」的警告?

雖然產量的問題問什麼,我得到了輸入和輸出,它說「Use of unitialized value in print at line 18, <> line 4」之間的警告。 我想我權利line 10數組。爲什麼我仍然收到警告?

1  #!/usr/bin/perl 
2  #exercise4_6_4 
3  use warnings; 
4  use strict; 
5 
6  print "Type in your list: \n"; 
7  my $input =<>; 
8  chomp $input; 
9  my $i=0; 
10  my @array; 
11  while ($input ne "") { 
12  $array[$i] = $input; 
13  $input =<>; 
14  chomp $input; 
15  $i++; 
16  }; 
17  while ($i !=0) { 
18  print $array[$i],"\n"; 
19  $i--; 
20  }; 
21  print "$array[$i]"; 

運行腳本顯示以下內容:

Type in your list: 
child 
books 
flight 

Use of uninitialized value in print at exercise4_6_4.pl line 18, <> line 4. 

flight 
books 
child 
+2

此外,以供將來參考...這可能是張貼代碼,而行是個好主意號碼在這裏。 :) – summea 2013-03-19 23:44:08

+0

「未初始化的值」並不意味着一個未聲明的標識符,這意味着'undef'。這不是在抱怨'@ array' - 陣列永遠是「初始化」 - 而是關於'$陣列[$ i]'。 – ruakh 2013-03-19 23:44:31

回答

3

因爲您的上一個$i++在第15行遞增$ i,循環結束,則第18行嘗試獲得$array[$i],但是您沒有在$ array [$ i]中存儲任何內容。

你可以添加一個$i-- if $i > 0線16 17之間和線來解決這個問題。

對於它的價值,你可以使用push和pop,而不必擔心增加計數器

use strict; 
use warnings; 

print "Type in your list: \n"; 
my @input; 
push @input,$_ while defined($_ = <>) && $_ ne "\n"; 
print pop @input while @input; 
+0

啊,對。我忘記了最後一個$我是數組中元素個數的一個加號!對不起,新手錯誤。非常感謝! – 2013-03-19 23:53:48

1

您可能只需要像這樣的東西線,以取代18行:

print $array[$i-1], "\n";

陣列有其侷限性。 :)

相關問題