跳轉到內容

Perl 程式設計/練習 2 答案

來自華夏公益教科書,開放的書籍,為開放的世界

A. 從鍵盤輸入

[編輯 | 編輯原始碼]

1. 答案

print "Input a line of text: ";
$text = <STDIN>;
print "\n";
print "You entered: $text\n";

2. 答案

my @lines;
for (my $i=0; $i<3; $i++) {
  print "Input a line of text:\n";
  chomp(my $line = <STDIN>);
  $lines[$i] = $line;
}
$" = "|";
print "@lines\n";

chomp 在這裡有什麼用?嘗試在沒有它的情況下執行程式。

3. 答案

my $line1 = readline STDIN;
my $line2 = readline STDIN;
my $line3 = readline STDIN;
chomp($line1, $line2, $line3);
print("| $line1 | $line2 | $line3 |\n");

從命令列輸入

[編輯 | 編輯原始碼]

答案

foreach (@ARGV) {
  print "$_\n";
}

從文字檔案輸入

[編輯 | 編輯原始碼]

答案

open my $file, "<", "foo.txt";
my @lines;
foreach (<$file>) {
  chomp($_);
  push(@lines, $_);
}
$" = "|";
print "@lines\n";
華夏公益教科書