in reply to How to pass blocks to subroutines

Anyway it doesn't work the way I expect it if i pass the block as argument to the function.
##!/usr/bin/perl use strict; use warnings; use Data::Dumper; my @items = qw ( 12 19 35 37 48 98 25 ); print Dumper [&selected (sub {($_ > 35)}, \@items)]; print Dumper [&selected2 (\@items)]; exit; sub selected { my ($func, $arr_ref) = @_; return grep $func, @$arr_ref; } sub selected2 { my $arr_ref = shift; die "selected: need an arrayref" unless (ref $arr_ref eq "ARRAY"); return grep {($_ > 35)} @$arr_ref; }

Replies are listed 'Best First'.
Re^2: How to pass blocks to subroutines
by Sidhekin (Priest) on Jun 12, 2004 at 17:13 UTC

    Almost there. You just need to dereference $func.

    Replace:

     return grep $func, @$arr_ref;

    ... with:

     return grep &$func, @$arr_ref;

    ($func is a reference, and so always true.)

    print "Just another Perl ${\(trickster and hacker)},"
    The Sidhekin proves Sidhe did it!

      Damn, thats an ugly error. Can't believe I missed it.
        When in danger, or in doubt, copy code verbatim, tweak it out.

        Sometimes, you need to just start over with some sorta working code, understand what it does, and go backwards to wards a goal of something you want working. :)

        Bart: God, Schmod. I want my monkey-man.