O'Reilly logo

Learning Perl Student Workbook, 2nd Edition by brian d foy

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Appendix C. Answers to Chapter 3 Exercises

Answer 3.1: This program is a lot like the first exercise on page 60 of Learning Perl. Instead of printing all of the lines in reverse order, you only have to print one line. You don’t know ahead of time how many elements the array will hold, so you can’t use the exact index of the element that you want. You do know that $#array_name represents the last index of an array, so the second-to-last must be one less than that:

#!/usr/bin/perl
use warnings;

@lines = <STDIN>;
print "The second to last line is: $lines[$#lines-1]";

That one has a subtle special case though. When there is only one element in the array, the last index (the value in $#lines) is 0, so 0 - 1 is -1, and instead of accessing a specific index, the -1 makes Perl count from the other side of the array. The element at index -1 is the last element, not the second-to-last element. You have to do this in a slightly different way:

#!/usr/bin/perl
use warnings;

@lines = <STDIN>;
if( $#lines > 0 ) {
	print "The second-to-last line is: $lines[$#lines-1]\n";
	}
else {
	print "There aren't enough lines for a second-to-last one!\n"
	}

You don’t have to do so much typing though, because you can index arrays from the end. If you use a negative index, you can start with the last element and work your way backward. Thus, the index -1 is the last element, and -2 is the next-to-last element:

#!/usr/bin/perl use warnings; @lines = <STDIN>; if( $#lines > 0 ) { print "The second-to-last line is: $lines[-2]\n"; ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required