Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw

comment on

( #3333=superdoc: print w/replies, xml ) Need Help??
Move the declaration of @dirlist after the nested sub (getAns), then pass it in as a hard reference:
sub getDirs() { sub getAns() { my ($dirlist) = @_; # new print qq(Enter a valid directory: ); chomp(my $ans = <STDIN>); if ($ans ne "") { if ($ans =~ m/foo/g) { push(@$dirlist, $ans); # note the @$dirlist &getAns; } else { print qq(That is not a valid directory!\n); &getAns; } } else { return @$dirlist; # note the @$dirlist } } my @dirlist; my @dirs = getAns(\@dirlist); # note the \@dirlist if (@dirs) { return @dirs; } else { die qq(No directories have been entered!\n); } }

For more information on hard references, take a look at perlref.

Just a stylistic note, you don't need to put the & on getAns to call if if you're already using () (the original has a line which read my @dirs = &getAns()). As a matter of fact, you should stay away from using & to call subroutines unless you understand how it's different from calling them with (). Calling with & makes @_ in the called subroutine an alias for @_ in the caller; () makes a copy instead. So changing the parameters in the subroutine could affect the variables used in the main program. This is probably not what you expect! Be careful. If I were you, I'd change the places in your code that call &getAns to getAns().

Anyway, hope this helps.

In reply to Re: Where to declare? by blackmateria
in thread Where to declare? by Rich36

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

  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or or How to display code and escape characters are good places to start.
Log In?

What's my password?
Create A New User
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (3)
As of 2021-06-13 23:56 GMT
Find Nodes?
    Voting Booth?
    What does the "s" stand for in "perls"? (Whence perls)

    Results (58 votes). Check out past polls.