On Mon, Jul 01, 2002 at 02:57:36PM +0000, sara starre wrote:
>
> I defintely like your syntax better, and yes I was trying to avoid the loop
> entirely. Unfortunately I can't get your solution to work:
>
> DB<1>
> main::r2(./x.pl:66): $_ [0] %= @{$_ [1]};
> DB<1>
> Modification of a read-only value attempted at ./x.pl line 66.
> Debugged program terminated. Use q to quit or R to restart,
> use O inhibit_exit to avoid stopping after program termination,
> h q, h R or h O to get additional info.
> DB<1>
>
> Seems it doesn't like you trying to modify $_ [0] ? Also will yours work
> with negative rotation like rotate(-3, \@a) ?
>
> also
>
> return [] unless @{$_ [1]};
>
> give a runtime error if $_[1] isn't an array ref- seems like you'd want to
> find another way to trap that error as you're trying to AVOID errors with
> that statement?
>
> Nice work I'd like to see this function. I hate looping but I couldn't see
> how to avoid it in this case with the negative possiblities plus the fact
> that the rotation parameter can exceed the array length- ie:
>
> my @a=qw(A B C);
> rotate(-14, \@a);
The $_ [0] %= @{$_ [1]}; was assuming the first argument was an lvalue.
And yes, the rotation value can be negative, or exceed the array size,
that's the whole point of the %!
You might want to try:
#!/usr/bin/perl -w
use strict;
use warnings 'all';
sub rotate {
return () unless $_ [1];
die "Not an array ref" unless "ARRAY" eq ref $_ [1];
return [] unless @{$_ [1]};
my $l = $_ [0] % @{$_ [1]};
[@{$_ [1]} [$l .. $#{$_ [1]}, 0 .. $l]]
}
my $array = ['A' .. 'E'];
for my $r (-15 .. 15) {
printf "Rotate %3d: @{rotate $r, $array}\n", $r;
}
__END__
Rotate -15: A B C D E A
Rotate -14: B C D E A B
Rotate -13: C D E A B C
Rotate -12: D E A B C D
Rotate -11: E A B C D E
Rotate -10: A B C D E A
Rotate -9: B C D E A B
Rotate -8: C D E A B C
Rotate -7: D E A B C D
Rotate -6: E A B C D E
Rotate -5: A B C D E A
Rotate -4: B C D E A B
Rotate -3: C D E A B C
Rotate -2: D E A B C D
Rotate -1: E A B C D E
Rotate 0: A B C D E A
Rotate 1: B C D E A B
Rotate 2: C D E A B C
Rotate 3: D E A B C D
Rotate 4: E A B C D E
Rotate 5: A B C D E A
Rotate 6: B C D E A B
Rotate 7: C D E A B C
Rotate 8: D E A B C D
Rotate 9: E A B C D E
Rotate 10: A B C D E A
Rotate 11: B C D E A B
Rotate 12: C D E A B C
Rotate 13: D E A B C D
Rotate 14: E A B C D E
Rotate 15: A B C D E A
Abigail