Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: storing records of data structure in perl?

by kcott (Archbishop)
on May 21, 2015 at 02:36 UTC ( [id://1127297]=note: print w/replies, xml ) Need Help??


in reply to storing records of data structure in perl?

G'day redss,

While your example code has hard-coded values, I'll assume you're actually capturing this data from some source (user input, spreadsheet extract, etc.) and have placed the vales in $name, $addr and $city.

Create a module for your class. 'my_type' is a poor choice of name: all lowercase names are typically used for pragmata and it's totally uninformative; for want of something better, I've used 'Client::Data' below.

Take a look at "Perl OO Tutorial for Beginners". It's entry level and you may have read it previously; however, it had a major revision in 2013 (possibly more recent than your last read) and provides links to more detailed and advanced information.

The six lines of code you posted can now be reduced to:

push @client_list, Client::Data::->new(name => $name, address => $addr, city => $city +);

Note that I've used an array (no dereferencing of an arrayref required) with a more informative name. A hash (perhaps %client_data_for) may be a better choice — see ++GotToBTru's comments above.

I don't know whether "access the values later" means later in the code or at a later time in other code. If the latter, ++Laurent_R has addressed this above.

Accessing the data is easy. It will, of course, depend on whether you've used an array or a hash. I've no idea how you intend to use this, but let's say you want to find Mary Smith's city. [Note: I've assumed Moose/Mouse/Moo style accessors and the example code is untested.]

my $wanted_client = 'Mary Smith';

Array:

for my $client (@client_data) { if ($client->name eq $wanted_client) { print "${wanted_client}'s city is ", $client->city; last; } }

Hash:

print "${wanted_client}'s city is ", $client_data_for{$wanted_client}- +>city;

From this, it should be obvious why a hash lookup is faster. Of course, a hash may be inappropriate for your needs.

-- Ken

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (4)
As of 2024-04-25 18:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found