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,
Erik

In reply to Re: Scoping issue when sorting with subroutines by erikharrison
in thread Scoping issue when sorting with subroutines by Dave05

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.