Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: Is list member

by ariels (Curate)
on May 06, 2002 at 08:15 UTC ( [id://164244]=note: print w/replies, xml ) Need Help??


in reply to Is list member

No, you cannot write a single function that will do both. You must have some notion of what "equality" means before you can write this function. Say we denote such equality (in English, not in Perl) with the symbol `~'. You'll need to decide e.g.

  • '10' ~ 10?
  • 'x10' ~ 0?
  • '' ~ 0?

It's also not clear from your question if you want the same function to work for finding both numbers in a number list and strings in a string list, or if you'd also like it magically to "do the right thing" when searching for a string in a number list etc.

Consider what you want to do, and then replace your problematic comparison e.g. with one of these:

  • "$_" eq "$item"
  • 0+$_ == 0+$item
  • The same, but <samp>local</samp>ly switching $^W off.

For an all-singing, all-dancing run-time customizable (and slower) solution, pass in a function to perform the comparison:

sub member(&@$) { my ($eq, $array, $item) = @_; for (@$array) { return 1 if $eq->($_, $item) } return undef; }

Finally, why are you trying to circumvent Perl's booleans? The use of things like $TRUE and $FALSE is a bad idea. First, builtins might not return these values, so you end up with 4 different values, and cannot do stuff like "return $a == $b" in the routine you pass to member. The values of TRUE and FALSE aren't going to change in the lifetime of your program; if they do, all your code will fall apart, so it doesn't matter. And note you're still using Perl's booleans, not yours:

... if ($_ eq $item)
should really test for truth, so it should be
... if ($_ eq $item) == $TRUE
which should really test for truth, so it should be
... if (($_ eq $item) != $FALSE) eq $TRUE
etc.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (5)
As of 2024-04-23 22:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found