in reply to Re^2: Variable scope
in thread Variable scope

Oh, and another use for state variables — caching/memoization. For example:

sub sort_network { state @mem; my $cmp = $mem[@_] //= do { ... }; my @res = @_[ @$cmp ]; }
I'm sure there are plenty more uses.

Replies are listed 'Best First'.
Re^4: Variable scope
by choroba (Cardinal) on Apr 06, 2018 at 09:42 UTC
    That's exactly what I warned against. Imagine you now need to sort two networks: how do you clear the cache before the second run?

    ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,

      Pardon me? That example would presumably return a sorting network or certain size and type; I'm not sure what you mean by "sort two networks". Memoization helps there because of recursive structure. I'll give another example that requires no explanation.

      sub fibonacci { my $n = shift; return 0+($n==1) if $n < 2; state @mem; $mem[$n] //= fibonacci($n-1) + fibonacci($n-2); }
      And before you ask: no, I do not foresee a need to produce two (different) Fibonacci sequences.

        Sorry, I didn't know about sorting networks.

        There are different kinds of Fibonacci sequences, and some of them are used in practice, e.g. in polyphase merge sort. You need to clear the cache when the number of runs or number of files changes.

        ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,