in reply to Controlling the start and endings of method calls

Well, you could reduce it to one line, and hide that line in another helper sub, I suppose. This method relies on the fact that if a sub is called with an '&' and without an explicit parameter list, it inherits @_ from its caller (see perlsub).

use strict; use warnings; package TestClass; sub _has_params { return @_ > 1 ? scalar(@_) - 1 : 0; } sub mytest { die "@_\n" if &_has_params; print "We're ok.\n"; } 1; package main; print "Testing with no parameters.\n\t"; TestClass->mytest( ); print "Testing with one parameter.\n\t"; TestClass->mytest( "Hello" );

There is one trick though, and I'm sure you're already dealing with it somehow: When a sub is called as a method (be it a class method or an object method) it will have one parameter passed into @_; either the class name or the self object ref. That's why in my "has_params()" subroutine, I only trigger a positive if there is more than one parameter.

When you run the snippet above you'll see that it passes the first test, and dies on the second one.


Dave

Replies are listed 'Best First'.
Re^2: Controlling the start and endings of method calls
by blazar (Canon) on Feb 02, 2006 at 11:06 UTC
    sub _has_params { return @_ > 1 ? scalar(@_) - 1 : 0; }

    How 'bout

    sub _has_params { @_ - 1 }

    ?

    It would also check if it is called as a sub with no arguments... oh, well, and it wouldn't catch a call like a sub with exactly one argument...

      But then if the 'method' was invoked as a sub from within the class it could potentially have no params, leading to a return value of -1, which would give a false positive.


      Dave

        Indeed. Just to make sure: I was more brainstorming than stating claims! However this directly leads us to discuss whether it is generally (i.e. with the exclusion of possible corner cases) a good practice to call a method like a sub even from within the same class, which at first sight IMHO is not by any means, but that would bring us too far away and in this moment I'm far too tired to even try to think of it...