Monday, 27 July 2009

Smart match to-do

The "new" smart match in Perl 5.10.1 can still be ameliorated.

Unlike what will happen with the changes between 5.10.0 and 5.10.1, which won't be backwards-compatible, the futher improvements to smart matching will be considered only if they don't break code. However the semantics can be extended.

Here's an example. The following code, that prints "ok" under 5.10.0, will now issue a run-time error :

use 5.10.1;
$obj = bless { foo => 42 };
say "ok" if 'foo' ~~ $obj;

The new error, Smart matching a non-overloaded object breaks encapsulation, which was suggested by Ricardo Signes, avoids to access by mistake the implementation details of an object.

However, from inside a method, it can be completely correct to use ~~ on the object's underlying reference. That's no longer possible in 5.10.1, unless you make a shallow copy of the object, for example with:
'foo' ~~ { %$obj }

Which won't be very performant if you have lots of keys there.

That's why I recently added in perltodo this little item:

Currently $foo ~~ $object will die with the message "Smart matching a non-overloaded object breaks encapsulation". It would be nice to allow to bypass this by using explictly the syntax $foo ~~ %$object or $foo ~~ @$object.

1 comment:

DECIBEL... said...

Q: I have an Array @arr which is dynamic in nature.
Assume at one pint @arr = qw(good better best) later the array becomes @arr=qw(good better) and some times it is @arr=qw(good worse)

When i iterate over the array i need to display the best stated one like in good better best the best stated one is best
similarly for the other two cases where the best stated is better and good

I dont want to use "grep" function neither any smart match operation. I am using Perl 5.8.

Just a curious to know can this be happened with foreach loop in perl.


if @arr is qw (good better best) -> best needs to be displayed
@arr is qw(good better) -> better needs to be displayed
@arr is qw(good worse)-. good needs to be displayed.


Please help me in this regard.

Looking forward to hear from you soon.