in reply to Nested subs - inherently evil?

Nested subs aren't. Both subs wind up with a slot in the current package's symbol table. The following two examples are more or less equivalent:

Example 1:

sub foo { my $foo_arg = shift; my $foo_return = bar( $foo_arg ); sub bar { my $bar_arg = shift; $bar_return = munge_munge( $bar_arg ); return $bar_return; } return $foo_return; }

Example 2:

sub foo { my $foo_arg = shift; my $foo_return = bar( $foo_arg ); return $foo_return; } sub bar { my $bar_arg = shift; $bar_return = munge_munge( $bar_arg ); return $bar_return; }

I know that structurally, they look different, but they aren't. That's because subs are global in nature and cannot be lexically scoped. They do have one subtle difference, though: they can throw strange "variable will not stay shared" errors if the inner sub tries to access lexically scoped variables. If, for some reason, you feel the need to do this, you want a reference to a sub:

my $sub_ref = sub { munge_munge( shift ) };

Then, you can lexically scope the sub reference and you won't have a problem. Whether or not that's appropriate in this case I will leave to wiser monks than I. However, I will point out that if you really want that sub to be more flexible, pass in the filehandle. (The following is untested)

open BINFILE, "<", "somefile.txt" or die $!; ReadBytes( $num, \*BINFILE ); sub ReadBytes { my ( $num, $binfile ) = @_; return undef if $num < 1; my @bytes; for (1..$num) { my $byte; read($binfile, $byte, 1); push @bytes, unpack("C",$byte); } return @bytes; }

Cheers,
Ovid

Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.

Replies are listed 'Best First'.
Re: (Ovid) Re: Nested subs - inherently evil?
by dragonchild (Archbishop) on Feb 11, 2002 at 20:31 UTC
    While glob-refs were all the rage, I'd prefer to be fashion-concious and use IO::File instead. :-)

    ------
    We are the carpenters and bricklayers of the Information Age.

    Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.