Sunday, February 17, 2013

Slices of method calls within an object

Several years ago I complained that object accessors prevent you from using some common Perl idioms; in particular, you couldn't take a slice of several attributes within an object.

Now I just discovered the Want module; this is great for playing with lvalue subroutines. With the help of this module, I was finally able to use slices of method calls within an object : see https://metacpan.org/module/Method::Slice . There are some caveats in comparison with a usual hash slice, but nevertheless the main point is there : you can extract some values :

  my @coordinates = mslice($point, qw/x y/);

or even assign to them:

  (mslice($point, qw/x y/)) = (11, 22);

This was written just for fun ... but in the end I might use it in real code, because in some situations, I find slices to be more compact and high-level than multiple assignment statements.

2 comments:

  1. See also Contextual::Return
    https://metacpan.org/pod/Contextual::Return

    ReplyDelete
    Replies
    1. The "Want" module not only tells if we are in lvalue context; it also has înformation about "ASSIGN" context, which was important for implementing mslice. Contextual::Return doesn't have this level of detail.

      Delete