in reply to Re^2: "Biochem BINGO" or "Noob Seeks Zen Thrashing"
in thread "Biochem BINGO" or "Noob Seeks Zen Thrashing"
I couldn't figure out how to pass a nested subroutine."pass" a sub? You didn't pass a sub. You defined it, then used it, then returned it's return value. If you want to pass a sub, you need a reference to it. Off the top of my head, there are 2 easy ways:
1) Define an anonymous (no-name) sub, and assign it to a scalar ref
2) Take a reference to a named submy $square_this = sub { my $x = shift; return $x**2; };
Use it like this (either version):sub square { my $x = shift; return $x**2; } my $square_this = \□
Perhaps what you really meant was nested sub, in the Pascal sense. In Perl there's no such animal per se, though it can be emulated. In Perl we could talk about a limited scope sub, only available to a certain sub or collection of subs. Again, a couple of ways:my $squared = $square_this->($hypotenuse);
1) Packages: define a package to limit scope
Use it one of these ways:package Square; sub square { my $x = shift; return $x**2; }
2) Outside of package Square, e.g., main:my $squared = square($hypotenuse);
3) If you do this, it won't be limited in scope.my $squared = Square::square($hypotenuse);
The solution I think you're looking for (and tell me if I'm wrong), is a closure with an anonymous sub, that can only be seen by your named sub. For instance:use Square qw(square); my $squared = square($hypotenuse);
Now only the subs (and other code) in the closure can see $square (unless you give out a reference to it).{ # closure for cubed my $square = sub { my $x = shift; return $x**2; }; sub cubed { my $z = shift; return $z*$square->($z); } } # end closure for cubed
-QM
--
Quantum Mechanics: The dreams stuff is made of
|
|---|