Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: Is it possible to store an arthimetric operator in a variable?

by Adam (Vicar)
on Jul 19, 2005 at 14:25 UTC ( #476116=note: print w/ replies, xml ) Need Help??


in reply to Is it possible to store an arthimetric operator in a variable?

Sure:

sub _eq($$){ $_[0] == $_[1] ? 1 : 0 } sub _ne($$){ $_[0] == $_[1] ? 0 : 1 } my $op = \&_eq; print $op->( 1, 2 ) ? 'EQ' : 'NEQ'";
Edit: mrborisguy beat me to this answer while I was contemplating using tie to do it.


Comment on Re: Is it possible to store an arthimetric operator in a variable?
Download Code
Re^2: Is it possible to store an arthimetric operator in a variable?
by ikegami (Pope) on Jul 19, 2005 at 14:46 UTC

    You shouldn't use prototypes unless necessary, because of their side-effects. In this case, the prototype isn't even being checked because you're using a reference to the function.

    And why bother with ?1:0 and ?0:1 since == already returns a boolean value.

      You are correct that the code isn't using the prototypes or requires the 1:0. I used them both, however, to be very clear to our anonymous reader what it was the code was doing. Also, I used 1:0 because I don't like using undef as a boolean false; it's not relevant here, but I find that 0 as false makes debugging easier which has led to this habit.
        Boolean false isn't undef. Notice the lack of warnings in the following snippet:
        >perl -we "print(1==2)" >
Re^2: Is it possible to store an arthimetric operator in a variable?
by Adam (Vicar) on Jul 19, 2005 at 17:27 UTC
    For those curious, this is how I might do it using tie.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://476116]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (13)
As of 2014-09-19 18:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (144 votes), past polls