Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: Working with Hashes (stored in other files)

by stevieb (Canon)
on Jun 12, 2016 at 12:57 UTC ( [id://1165418]=note: print w/replies, xml ) Need Help??


in reply to Working with Hashes

This sounds like data sharing, for which I'd use JSON (it's cross-language).

I've included an example script that shows you how you write JSON to a file called write.pl.

I then show the resulting JSON data in the file, then a script fetch_hash.pl that reads in the data using a command line argument.

write.pl

use warnings; use strict; use JSON; my %first_hash = (fruit => 'banana', Vegetable => 'tomato'); my %second_hash = (work => 'office', family => 'home'); my %hashes = ( first_hash => \%first_hash, second_hash => \%second_hash, ); my $json = encode_json \%hashes; open my $fh, '>', 'data.json' or die $!; print $fh $json;

data.json (JSON file)

{"second_hash":{"work":"office","family":"home"},"first_hash":{"Vegeta +ble":"tomato","fruit":"banana"}}

fetch_hash.pl

use warnings; use strict; use Data::Dumper; use JSON; if (! @ARGV && ($ARGV[0] ne 'first_hash' || $ARGV[0] ne 'second_hash') +){ print "need first_hash or second_hash as arg\n"; exit; } my $want = $ARGV[0]; my $file = 'data.json'; my $json; { local $/; open my $fh, '<', $file or die $!; $json = <$fh>; close $fh; } my $data = decode_json $json; print Dumper $data->{$want};

Output:

$ perl fetch_hash.pl first_hash $VAR1 = { 'fruit' => 'banana', 'Vegetable' => 'tomato' }; $ perl fetch_hash.pl second_hash $VAR1 = { 'work' => 'office', 'family' => 'home' };

Replies are listed 'Best First'.
Re^2: Working with Hashes (stored in other files)
by Anonymous Monk on Jun 14, 2016 at 12:34 UTC

    Thanks for the code.

    Unfortunately in my environment I do not have JSON package installed.

    Can you help me with the steps how can I get the JSON package installed?

    Thanks again for your help.

      Above is the reply from my side, I replied without logging in :) ..

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1165418]
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: (8)
As of 2024-04-23 12:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found