A
A
artem782014-09-01 23:46:28
Perl
artem78, 2014-09-01 23:46:28

How to use a constant as a hash key in perl?

You need to pass parameters for curl to the function. It makes sense to put them in a hash, but perl interprets constants as a key as a string, and the setopt function quite rightly reports "Argument "CURLOPT_URL" isn't numeric in subroutine entry". How to be?

use WWW::Curl::Easy;
use Data::Dumper;

my %opts = (
  CURLOPT_URL => 'http://wikipedia.org',
  CURLOPT_CONNECTTIMEOUT => 30
);

sub curl_func {
  my ($curlOptions) = @_;
  my $ch = new WWW::Curl::Easy();
  while (my ($key, $value) = each %$curlOptions) {
    $ch->setopt($key, $value);
  }

  # ....
}

curl_func(\%opts);

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Slipeer, 2014-09-02
@artem78

Perl constants are actually functions that return the desired values.
Accordingly, to call a function by name:

use WWW::Curl;
use WWW::Curl::Easy;
use Data::Dumper;

my %opts = (
    CURLOPT_URL => 'http://wikipedia.org',
    CURLOPT_CONNECTTIMEOUT => 30
);

sub curl_func {
    my ($curlOptions) = @_;
    my $ch = new WWW::Curl::Easy();
    while (my ($key, $value) = each %$curlOptions) {
        $ch->setopt(&{$key}(), $value);
    }
    # ...
}

curl_func(\%opts);

P
Ptktysq, 2014-10-03
@Ptktysq

my %opts = (
    CURLOPT_URL() => 'http://wikipedia.org',
    CURLOPT_CONNECTTIMEOUT() => 30
);

And similarly when using a constant as a hash key:
In other cases, the brackets are optional.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question