cluka has asked for the wisdom of the Perl Monks concerning the following question:

We're all familiar with the perl operators map and grep...
map { ...code here... } @array
I'd like to create a similar function called &partition that accepts a block of code and acts on an array in similar fashion. I've tried several approaches, most promising of which was
# Predeclaration sub partition($\@); ... sub partition($\@){ my ($coderef, @array) = @_; # Do something with these variables }
Unfortunately, this doesn't work - typing partition {...} @a just generates a syntax error.
Is what I'm attempting impossible, or am I just not seeing something?
Chris Luka

Replies are listed 'Best First'.
Re: Creating operators in the flavor of map & grep...
by DamnDirtyApe (Curate) on Sep 04, 2002 at 23:55 UTC
Re: Creating operators in the flavor of map & grep...
by shotgunefx (Parson) on Sep 04, 2002 at 23:49 UTC
    The prototype should be partition(&\@) and the array will be passed by ref so it should be my ($coderef,$arrarref) = @_;

    -Lee

    "To be civilized is to deny one's nature."
      I would recommend using (&@) as a prototype. That way you can use a list for other arguments. If you use ($\@) your second argument must be an array.
      use strict; use Data::Dumper; sub takes_coderef (&@); takes_coderef {print "I'm a code ref called with (", join(", ", @_), " +)\n"} "first", 2, 3; sub takes_coderef (&@) { my $coderef = shift; my @otherargs = @_; &$coderef(@otherargs); print Data::Dumper->Dump([\@otherargs], ["*otherargs"]); } ___OUTPUT___ I'm a code ref called with (first, 2, 3) @otherargs = ( 'first', 2, 3 );
      See this thread about prototypes and especially Tom Christiansen's Prototypes in Perl for a very in-depth discussion of prototypes.

      --

      flounder

        For most purposes your probably right. Myself, I've mainly written map|grep like functions for lazy iteration so I've needed the reference to the data.

        -Lee

        "To be civilized is to deny one's nature."