Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I "store" an operator inside a variable in Perl?

Tags:

perl

I'm looking for a way to do this in Perl:

$a = "60"; $b = "< 80";

if ( $a $b ) {  then .... }

Here, $b "holds" an operator... can I do this? Maybe some other way?

like image 752
Ricky Levi Avatar asked Mar 21 '10 09:03

Ricky Levi


People also ask

Can we store operators in variable?

You cannot store an operator in JavaScript like you have requested. You can store a function to a variable and use that instead.

What is $@ in Perl?

$@ The Perl syntax error or routine error message from the last eval, do-FILE, or require command. If set, either the compilation failed, or the die function was executed within the code of the eval.

How do I store a variable in Perl?

Perl variables do not have to be explicitly declared to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables.

Why $_ is used in Perl?

Note: The most common special variable is $_, which is used to store the default input.


2 Answers

It's nice to see how people discover functional programming. :-)

Luckily, Perl has capabilities to create and store functions on-the-fly. For example, the sample in your question will look like this:

$a = "60"; $b = sub { $_[0] < 80 };

if ( $b->($a) ) { .... }

In this example, a reference to the anonymous subroutine is stored in $b, the sub having the same syntax for argument passing as a usual one. -> is then used to call-by-reference (the same syntax you probably use for references to arrays and hashes).

But, of course, if you want just to construct Perl expressions from arbitrary strings, you might want to use eval:

$a = "60"; $b = " < 80";

if ( eval ("$a $b") ) { .... }

However, doing this via eval is not safe, if the string you're eval-ing contains parts that come as user input. Sinan Ünür explained it perfectly in his answer-comment.

like image 68
P Shved Avatar answered Oct 24 '22 11:10

P Shved


How about defining a function that wraps the needed condition:

my $cond = sub { $_[0] < 80 };

if ( $cond->( $a ) ) { 
     ...
}
like image 22
friedo Avatar answered Oct 24 '22 12:10

friedo