perl: Fibonacci with hash values.
This is my first real code written in perl, and I must say it's rather satisfying, it's a simple fibonacci calculator using a hashtable (hash value).
So, here's the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#!/usr/bin/perl
%table = (0 => 1, 1 => 1);
for ($i = 0;$i < 30;$i++) {
print "fibo for ".$i.": ".fibo($i)."\n";
}
sub fibo{
my($f) = $_[0];
if ($f < 0) {
print "Input is less than 0: ".$f."\n";
return -1;
}
if (exists $table{$f}) {
return $table{$f};
}
else {
if (not exists $table{$f - 2}) {
$table{$f - 2} = fibo($f - 2);
}
if (not exists $table{$f - 1}) {
$table{$f - 1} = fibo($f - 1);
}
$table{$f} = $table{$f - 2} + $table{$f - 1};
return $table{$f};
}
}
What's interesting is the use of my($var) for reassigning parameters to the function to internal variables. Moreover the if and else statements demands {} after the condition, which I mostly like as optional. Besides that it looks like a neat language for writing scripts and regex statements.
One thing I'm lacking at the moment (should be obvious) is a way of concatenating things into a string, to avoid mass printing everything in a separate function call.