Perl Programming/Exercise 2 Answers

From Wikibooks, open books for an open world
< Perl Programming
Jump to: navigation, search

A. Input from the keyboard[edit]

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.

Input from the command-line[edit]

Answer:

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

Input from a text file[edit]

Answer:

open my $file, "<", "foo.txt";
my @lines;
foreach (<$file>) {
  chomp($_);
  push(@lines, $_);
}
$" = "|";
print "@lines\n";