EDIT: I'm glad no one has spent any time pointing out that the actual text in line 6 and 7 has a different number than the input for their respective function calls. Eventually I'll be doing it for those two numbers (724 and 27), but for the sake of troubleshooting, I picked numbers with much smaller sequences. So, if anyone was wondering, that's why...
So, I've been learning Perl, and am relatively new to programming in general. My supervisor has a set of exercises for me to go through. The current one deals with Hailstone sequences, and she wants me to write a subroutine that prints the sequence for a given number.
The problem I'm running into is that, no matter what I've tried, if I call the function more than once, it will produce the sequence for the first number I call the function with, but the second time I call the function, it produces the sequence of the first call followed by the sequence of the second. So, this code:
#!usr/bin/perl
use strict;
use warnings;
print "\nThe hailstone sequence for 724 is:\n" . &hail(8) . "\n\n";
print "The hailstone sequence for 27 is:\n" . &hail(16) . "\n\n";
my $n;
my @seq;
sub hail {
no warnings 'recursion';
$n = $_[0];
if ($n > 1) {
push @seq, $n;
if ($n % 2 == 0) {
$n = $n/2;
} else {
$n = (3 * $n) + 1;
}
&hail($n);
} else {
push @seq, $n;
}
return "@seq";
}
produces:
The hailstone sequence for 724 is:
8 4 2 1
The hailstone sequence for 27 is:
8 4 2 1 16 8 4 2 1
I understand that this is most likely due to the fact that @seq
doesn't get cleared out after each time the subroutine runs, but I've tried as many different ways as I can think of to clear it out so that each time I call the subroutine, it displays the sequence for -only- that number but they all either result in what I show here, or in showing nothing. How do I go about clearing the array each time?
Thanks very much.
&
to call subroutines in Perl. That's an old and obsolete practice (except in certain advanced and obscure instances you don't need to worry about yet). Just usehail(8)
. – Crusadereturn "@seq"
? – Rustice@seq
and"@seq"
produce two different things, and"@seq"
was working for what I was trying at the time. There's another part of the exercise where I do need the number of elements in a given sequence, andreturn @seq
is working beautifully for that, now I'm just working back from that to actually display the sequence. – Blackstock