Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Get element of array not looping.

by Anonymous Monk
on Jul 13, 2021 at 17:53 UTC ( [id://11134968]=perlquestion: print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,

Whats the way to manually access the firt element of this arrays without looping?

Test Code:

#!/usr/bin/env perl use strict; use warnings; my $DATA = { "facts": [ { "name": "A", "type": "Normal" }, { "name": "B", "type": "Broken" } ], }; print $DATA->{ facts }->{ name }->[0]; # A print $DATA->{ facts }->{ type }->[0]; # Normal exit;
Thanks for looking!

Replies are listed 'Best First'.
Re: Get element of array not looping.
by choroba (Cardinal) on Jul 13, 2021 at 17:59 UTC
    syntax error at ./script.pl line 8, near ""facts":"

    Perl can parse JSON, but only from a string, not directly from the source code. In Perl hashes, keys are separated by commas or fat commas from the values, not colons. Then, you can do:

    my $DATA = { facts => [ { name => 'A', type => 'Normal' }, { name => 'B', type => 'Broken' } ], }; print $DATA->{facts}[0]{name}; # A print $DATA->{facts}[0]{type}; # Normal

    It's a hash containing an array containing hashes, not a hash of hashes of arrays.

    Or, parse the JSON, but remove the trailing comma after the array, JSON doesn't support it:

    #!/usr/bin/perl use warnings; use strict; use Cpanel::JSON::XS; my $DATA = decode_json('{ "facts": [ { "name": "A", "type": "Normal" }, { "name": "B", "type": "Broken" } ] }'); print $DATA->{facts}[0]{name}; # A print $DATA->{facts}[0]{type}; # Normal

    map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]
      Perfect, thank you!!!
Re: Get element of array not looping.
by AnomalousMonk (Archbishop) on Jul 13, 2021 at 22:40 UTC

    More info on working with complex Perl data structures (once you get them into the right syntax :) is found in the Perl Data Structures Cookbook (perldsc).


    Give a man a fish:  <%-{-{-{-<

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://11134968]
Approved by choroba
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (4)
As of 2024-04-23 16:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found