Sure it is! Just put the sub declarations in another package, use package at the top of your main code, and then use a fully qualified package name in place of up and down. However, since the code for these two subs is small, and refers to a specific variable in a wider scope, this may not be a good idea. Here is a rewrite of the sort_em sub that may point out why.
sub sort_em { my %nos = @_; #Don't make a ref just to deref it, just #pass the hash. Use 'my' to indicate #lexical scope print "UP:\n"; print join "\n", sort { $nos{$a} <=> $nos{$b} } keys %nos; #just p +ass in short sorting routines on the line #of the sort print "\n\nDOWN:\n"; print join "\n", sort { $nos{$b} <=> $nos{$a} } keys %nos; #same a +s above }
Note that the declaration of the subs up and down inside the braces of sort_em does not make them lexically scoped.
Cheers,In reply to Re: Scoping issue when sorting with subroutines
by erikharrison
in thread Scoping issue when sorting with subroutines
by Dave05
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |