Friday, December 10, 2010

Day 10: Can't call method "..." on an undefined value

Are you tired of these error message?

It occurs when you chain methods and one of them returns 'undef' - or when you just call methods on an undefined value.
perl -e 'undef->x'

If "$a->b->c" throws this message you can rewrite it as "$a->b && $a->b->c". But how boring is this?

Scalar::Andand to the rescue! Now you can write "$a->b->andand->c".

It's important to quote the documentation:
Note that this module was intended as a proof of concept. The author has never used it in production code, nor is he planning to do so.

I continue tomorrow with "serious" stuff. :)

Links:

4 comments:

  1. I am thinking what is the advantage against:

    my $result = eval { $a->b->c };

    But I am glad to see that I am not only one who runs often into this "call on undefind value" problem.

    ReplyDelete
  2. Roman, you are totally right. Scalar::Andand is just a "proof of concept". I do not use it myself. But I think it is a funny module. :)

    ReplyDelete
  3. I handle this sort of thing by returning null objects that returns itself for every method called. If the result ends up with a null object, something went wrong. You can even spruce it up a bit to have the null object carry along the first error so you can inspect it.

    ReplyDelete
  4. This little module of mine keeps garnering attention. Perl 5.14 will probably have syntax for this (probably &&->, though there is some bikeshedding about it).

    ReplyDelete

Note: Only a member of this blog may post a comment.