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.

      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";
      
      Last modified on 13 April 2011, at 09:04