Manipulating the Array Ends
Listing 3.2 shows a program that reads a list of numbers from the user and creates an array out of them.
Listing 3.2. read1.pl
# Note: This program is inefficient use strict; use warnings; my @array = (); # The list of numbers we have read while (1) { print "Input number or <Enter> to finish: "; my $answer = <STDIN>; chomp($answer); if ($answer eq "") { last; } @array = (@array, $answer); } |
The problem is the following line:
@array = (@array, $answer);
This takes the array @array and the scalar $answer and combines them into an array expression. This array expression is then assigned to @array. Because you are computing a new array and doing an entire replacement, this is inefficient.
A more efficient way of doing ...
Get Perl for C Programmers now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.