Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

Re^2: Why does this sub grab the whole hash

by naturalsciences (Beadle)
on Nov 11, 2011 at 18:04 UTC ( #937644=note: print w/replies, xml ) Need Help??

in reply to Re: Why does this sub grab the whole hash
in thread Why does this sub grab the whole hash

Done this thing a lot already :D

print $hashofseqs{someIDnr}, "\n";

gives me what I expect, a nice little sequence from my hash. The one sequence which has the key someIDnr. The other part gives me a looong output where there is every single sequence ran through the subroutine. Hmm actually even multiple times.

Replies are listed 'Best First'.
Re^3: Why does this sub grab the whole hash
by davido (Archbishop) on Nov 11, 2011 at 18:06 UTC

    @dr is not lexically scoped. The result is that each time the sub is called, unless you're reinitializing it somewhere that we're not seeing, @dr still has cruft in it from previous calls to the subroutine. It probably needs to be declared as my @dr.

    $done is also not lexically scoped, but that's not as important as you're doing an assignment to it rather than an append. push is like an append for an array. If the array already has junk in it, you're just adding to what's already there.


      Oh man - enlightenment just hit me. Looked over my code and now I got how this poor array was filled over and over again with some quite random stuff in the different parts of my script. Really bad idea to use a subs like this with a globally defined array.

        And that's why people always recommend to use strict; -- it complains about undeclared variables, so it forces you to think about where to put the declaration. And you only put the declaration outside the subroutine if that's your conscious choice.

        Really bad idea to use a subs like this with a globally defined array.

        It's a really bad idea to use subs (or anything else) with a globally defined, non-constant anything unless, as moritz has written, it's your conscious decision to do so — and even then I'd think twice about it.

      Changing the subs code to..

      sub revcompl { my (@dna) = @_; my @dr=(); foreach my $segment (@dna) { my $revcomp = reverse($segment); $revcomp =~ tr/ACGTacgtMKRYBDHVmkrybdhv/TGCAtgcaKMYRVHDBkmyrvhdb/; push @dr, $revcomp; } $done = join('',@dr); return $done; }

      Worked out well. Thank you very much. The behaviour noticed before still weirds me out, guess it's time to study some more. Any more enlightening comments on what happened there are welcome by everybody :D

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://937644]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (2)
As of 2018-04-22 07:17 GMT
Find Nodes?
    Voting Booth?