开发者

How to access elements in this data structure?

I have a variable called $ip_data and when I do 'print $ip_data;' it shows something like this: ARRAY(0x3c353cc4);

Data::Dump gives me the following structure:

[
 {
   ip => "127.0.0.1",
   list => [
     "France",
     "Safari",
   ],
 },
]

I would like to extract ip (IP address), country and browser and put it in a hash that looks like this:

%ip_info = (  ip       => '127.0.0.1',
              country  => 'France',
              browser  => 'Safari' );

So far all my attempts to dereference it have failed. As I understand it $ip_data is an array that has a hash for an element, and that hash's first element is a string, but the second is an array holding开发者_C百科 two string elements.

Am I wrong about it? If so please tell me what's going on here and how to get those elements in %ip_info.


$ip_data is a reference to array containing a single element (a hash reference). You can construct your hash like this:

my %ip_info = (
    ip      => $ip_data->[0]{ip},
    country => $ip_data->[0]{list}[0],
    browser => $ip_data->[0]{list}[1],
);

I suggest you to read the perlref manual page to find out more about using references in Perl.


eugene y's answer gives you your specific use case. To learn more read perldoc perlreftut and for the full story perldoc perlref

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜