Perl Programming/Exercise 2 Answers
A. Input from the keyboard
1. Answer:
print "Input a line of text: "; $text = <STDIN>; print "\n"; print "You entered: $text\n";
2. Answer:
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";
What is chomp there for? Try running the program without it.
3. Answer:
my $line1 = readline STDIN;
my $line2 = readline STDIN;
my $line3 = readline STDIN;
chomp($line1, $line2, $line3);
print("| $line1 | $line2 | $line3 |\n");
Input from the command-line
Answer:
foreach (@ARGV) {
print "$_\n";
}
Input from a text file
Answer:
open my $file, "<", "foo.txt";
my @lines;
foreach (<$file>) {
chomp($_);
push(@lines, $_);
}
$" = "|";
print "@lines\n";