First timer...so let me know if there is anything that I have not paid attention to whilst posing a question.
The question is how to use a scalar as a condition, as the code below does not work.
my @parameter=('hub');
my %condition;
$condition{'hub'}{'1'}='$degree>=5';
foreach (@parameter) {
if ($condition{$_}{'1'}) {..}
}
I thought that is because the condition is not interpreted correctly, so I also tried the following, which also did not work.
if ("$condition{$parameter}{'1'}") { ..}
Would really appreciate any help. :)
What you are trying to do is to evaluate '$degree>=5' as real code. Rather than trying to evaluate the string as code (which can be done with eval), it's usually safer and often more robust to instead pass a code-reference. You can use a generator subroutine to generate conditional subs on demand, like this:
It gets a little more tricky if you want the
>=
(ie, the relationship itself) to be dynamically created as well. Then you have a couple of choices. One takes you back to stringy eval, with all of its risks (especially if you start letting your user specify the string). The another would be a lookup table within yourgenerate_condition()
sub.generate_condition()
returns a subroutine reference that when invoked, will evaluate the condition that was bound in at creation time.Here's a generalized solution that will accept any of Perl's conditionals and wrap them along with the arguments being tested into a subroutine. The subref can then be invoked to evaluate the conditional:
Often when you construct these sorts of things one is interested in leaving one parameter open to bind at call-time rather than at subroutine manufacture-time. Let's say you only want to bind the "
$bound
" and "$relation" parameters, but leave "$test
" open for specification at subroutine call time. You would modify your sub generation like this:And then invoke it like this:
If the goal is to provide late binding of both the lefthand and righthand side in the relational evaluation, this will work:
This sort of tool falls into the category of functional programming, and is covered in beautiful detail in Mark Jason Dominus's book Higher Order Perl
What are you expecting? String values are interpreted as
true
when they are nonempty.If you want to dynamically evaluate code in your conditions, you have to investigate
eval
. Example:prints
You either want string eval, which evaluates a string as Perl code
or perhaps a more secure approach would be using code references
In the second example, you are attaching a piece of code to a variable. The
$var->()
syntax executes the code and evaluates to the return value of the code.