I want to define a Perl function (call it "difference") which depends on a command-line argument. The following code doesn't work:
if ("square" eq $ARGV[0]) {sub difference {return ($_[0] - $_[1]) ** 2}}
elsif ("constant" eq $ARGV[0]) {sub difference {return 1}}
It appears that the condition is ignored, and therefore the "difference" function gets the second definition regardless of the value of $ARGV[0].
I can make the code work by putting a condition into the function:
sub difference {
if ("square" eq $ARGV[0]) {return ($_[0] - $_[1]) ** 2}
elsif ("constant" eq $ARGV[0]) {return 1}
}
But this is not really my intention -- I don't need the condition to be evaluated each time during execution. I just need a way to influence the definition of the function.
My questions are:
- Why does the first construction not work?
- Why does it not give an error, or some other indication that something is wrong?
- Is there a way to conditionally define functions in Perl?