The immediate 'problem' is that the for loop variable ($_ in your case) is an alias to each element in turn of the list being iterated over. It really isn't the same $_ that is used outside the loop. The same thing happens with $_ in map and grep. If you really want to retain the last processed value in a for loop you need to copy it to another variable explicitly:

sub traverse { my $result; for my element (@_) { ... $result = 'my interesting value to be retained on the last ite +ration'; } return $result; }

You really, really, really ought to use a variable instead of the default variable for your for loop variable btw. Using the default variable for more than a couple of lines and expecting it not to change by magic is just asking for trouble!

Oh, and you should use the three parameter version of open and lexical file handles:

open my $outputFile, '>', $output or die "Failed to create $output: $! +\n";

True laziness is hard work

In reply to Re: Modifying a parameter to a recursive function by GrandFather
in thread Modifying a parameter to a recursive function by CoDeReBeL

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.