in reply to Array ending up empty when processing more than a single file

The sub keyword will only define the subroutine once, and to be able to write on @flankseq it will hold a reference to the variable (because otherwise, @flankseq being lexical, it could be destroyed although the function always needs it). So while you create a new @flankseq in each loop, the function always uses the same one. This is demonstrated by:

$\ = $/; for (1..2) { my $var = 1; print \$var, " created"; sub function { print \$var; } function(); }
SCALAR(0x825d70) created SCALAR(0x825d70) SCALAR(0x96ec08) created SCALAR(0x825d70)
The solution is to define seqstore outside of the loop (it's not actually required, it's just better practice) and pass the array as a paramater (as a reference, so that it is passed all at once).
sub seqstore { my ($flankseq, $mode, @rcd) = @_; if ($mode eq "Pos") { push (@$flankseq, $rcd[0]); } elsif ($mode eq "Freq") { push (@$flankseq, $rcd[0]) for (1..$rcd[1]); } return; }
Now you have to call the function like that: seqstore(\@flankseq, $mode, $seqEX,$F[2]);

More info on closures, and on references

Replies are listed 'Best First'.
Re^2: Array ending up empty when processing more than a single file
by Your Mother (Archbishop) on Oct 05, 2017 at 16:12 UTC
    The sub keyword will only define the subroutine once

    This is interesting and, to me at least, unexpected. Why does this only warn once instead of twice?

    perl -wle 'for(1,2){ sub moo{} }; sub moo{}' Subroutine moo redefined at -e line 1.

      Well for the same reason as my example, the inner sub is only applied once, so only the second sub is a redefinition.

      I didn't find where the fact that a given definition of a sub (except anonymous of course) will only be applied once, no matter how often the scope of its definition is entered (actually I don't think the place where a function is defined matters at all, except for namespace and during compilation), but Lexical Subroutines explains how to create what you might expect (lexically scoped function, with redefinition each time), and so implies that the normal behaviour is different.

        I'm confused ... isn't this the old "won't stay shared" discussion?

        Named subs are defined at compile time, that's why you can call a sub which is defined later.

        A closure can only "share" the set of closed over variables it sees at definition time.

        (i.e. name and reference are added to the "lexical pad" compare PadWalker)

        That's why nesting named subs are discouraged in Perl.

        edit

        But when using an anonymous sub, the definition happens at run time.

        something like

         *name = sub {...} would solve this.

        Cheers Rolf
        (addicted to the Perl Programming Language and ☆☆☆☆ :)
        Je suis Charlie!