2

I'm using Sphinx::Search.

Is there is a easier way for this code example to convert a string to a constant?

use Sphinx::Search;

my $config = {
    x => 'SPH_MATCH_EXTENDED2',
};

my $x = $config->{x};
print Sphinx::Search->$x(); # output: 6

I have used advice from How do I access a constant in Perl whose name is contained in a variable? and this example works, but if I am always using a string from a hash then do I need to put it into a separate variable to use it in this way?

my $x = $config->{x};
print Sphinx::Search->$x(); # output: 6

Is there a one- liner for this?

# does not work
print Sphinx::Search->$config->{x}();
Borodin
  • 126,100
  • 9
  • 70
  • 144
crazywulf
  • 213
  • 2
  • 5
  • It's often easier to read to do the long version, as long as you use a proper descriptive variable name. `my $method = $config->{x}; print Foo->$method()` is totally acceptable. Shorter code is rarely better code. Remember that the most expensive part of your code is neither writing nor running it, but actually the time of other developers spent reading and understanding what the heck is going on. – simbabque Sep 21 '18 at 13:30
  • Those are not _constants_. `$x` is still a variable. The syntax parser just does not allow any expression after the `->`. It has to be atomic. If you want an actual _constant_, you'd have to create a new named sub with a prototype at runtime, possibly using inlining with string `eval`. – simbabque Sep 21 '18 at 13:32

2 Answers2

3

You can create a reference to the value and immediately dereference it:

Sphinx::Search->${ \$config->{x} };

(If there are no arguments, the () is optional).

choroba
  • 231,213
  • 25
  • 204
  • 289
-1

I'm guessing that SPH_MATCH_EXTENDED2 is the name of a constant that is exported by Sphinx::Search. The problem is that these are implemented as a subroutine with no parameters, so you may use them only where a bare subroutine name will be understood by Perl as a call, or where an explicit call is valid ( SPH_MATCH_EXTENDED2() )

The easiest solution is to avoid quoting the hash value at all, like so

my $config = { x => SPH_MATCH_EXTENDED2 }

and afterwards, you may use just

$config->{x};    # 6

instead of calling a pseudo class method

Borodin
  • 126,100
  • 9
  • 70
  • 144