Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re^4: index of the minimum element of the array

by ikegami (Pope)
on Jan 17, 2014 at 18:23 UTC ( #1070998=note: print w/ replies, xml ) Need Help??


in reply to Re^3: index of the minimum element of the array
in thread index of the minimum element of the array

You're accessing the callback's @_ when you mean to access minindex's


Comment on Re^4: index of the minimum element of the array
Select or Download Code
Re^5: index of the minimum element of the array
by oiskuu (Friar) on Jan 17, 2014 at 18:33 UTC

    I'm passing a block to reduce.

      Ikegami is right, thats not working!

      Better pass the list as a closed over array (here @x)

      DB<109> @a= map { int rand 100 } 1..10 => (96, 10, 99, 9, 43, 8, 20, 85, 42, 26) DB<110> sub minindex { my @x=@_; reduce { $x[$a] < $x[$b] ? $a : $b } 0 .. $#_ } DB<111> print minindex @a 5

      update

      or even better like ikegami now suggested as ref to avoid overhead

      DB<114> @a= map { int rand 100 } 1..10 => (22, 15, 27, 44, 70, 85, +74, 93, 96, 14) DB<115> sub minindex { my $x=\@_; reduce { $x->[$a] < $x->[$b] ? $a : $b } 0 .. $#_ } DB<116> print minindex @a 9

      Cheers Rolf

      ( addicted to the Perl Programming Language)

        Don't copy @_, take a reference to it.
      Impossible. There's no such data type. You are passing a sub reference to reduce.
      reduce BLOCK LIST
      is compiled as
      &reduce(sub BLOCK, LIST)

        Fair enough. However, the sub is called with inherited @_ and it happens to work.

        Same thing with map:

        sub foo { map { print $_[$_] } 0 .. $#_ }
        Can I not rely on this behavior?

        Update. example code:

        use List::Util 'reduce'; sub minindex { reduce { $_[$a] < $_[$b] ? $a : $b } 0 .. $#_ } my @g = (55, 88, 33, 6, 234, 234, 52, 6, 1324, 22, 1234); print minindex @g; # $g[7] == 6
        This is perl 5, version 12, subversion 3 (v5.12.3) built for x86_64-linux-thread-multi
        List::Util $VERSION = "1.22";

        Update2. One final observation:
        I also see coderef passed to the sub when run under debugger. But not when run normally.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1070998]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (13)
As of 2015-07-02 11:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (34 votes), past polls