Paul Archer wrote:

> 4:09pm, Ramprasad A Padmanabhan wrote:
>
> And the problem is not simply a puzzle, nor is it homework. If you had read
> my post more carefully, you would see that I am 1) *teaching* the class, and
> 2) want to be able to show off one concept (the range operator) before we
> have talked about another concept (the 'reverse' statement).

Even more reason, if you are in the position of a teacher, not to use the range
operator for this purpose.  It is simply inappropriate.  Unless there is only a
certain subset of elements in the array for which you want to do magic, the foreach
(@array_name) format communicates intent much more clearly.

I'm a little surprised that no one has yet posted what seems to me the most direct
and transparent soltion:  [note the sample does make use of the range operator in a
more appropriate context]

Greetings! E:\d_drive\perlStuff>perl -w
my @keeper = (1..15);
{
  my @temp;
  push @temp, pop @keeper while @keeper;
  @keeper = @temp;
}
print "$_ " for @keeper;
^Z
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1

I like the above because:

1.  It is transparent. You can "see" the data being moved.
2.  It is process efficient.  Each element is moved only once, and an array name is
redirected.  It does what it takes--no more and no less.
3.  It minimizes memory demands painlessly.  The original storage for @keeper is
returned to the store when it is re-assigned, and @temp disappears entirely outside
the {...} closure, leaving @keeper pointing to the reversed array.

Hmmm...

On second thought, I'm not sure about process efficiency here, Perl may re-copy the
whole array in the assignment.  In which case, the more efficient and elegant
solution would use references:

Greetings! E:\d_drive\perlStuff>perl -w
my $keeper = [1..15];
{
  my $temp = [];      # " = []"  Not strictly neccesary.  The first push() would
autovivify @$temp
  push @$temp, pop @$keeper while @$keeper;
  $keeper = $temp;
}
print "$_ " for @$keeper;
print "\n";
^Z
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1

As a side exercise, you might have your students add the implicit parens.

Joseph



-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to