in reply to How can one access all the details of a person using arrays & hash?
Distributing the data for a single student across multiple arrays is asking for trouble. Much better to keep each student’s data in the same structure. So I would reverse the architecture: instead of a hash of arrays, use an array of hashes. Or, more precisely, an array of blessed hashes (objects). Something like this:
#! perl use strict; use warnings; { package Student; sub new { my ($class, $name, $age, $regd_no, $phone_num, $mark, $pass_year) = @_; my $self = { NAME => $name, AGE => $age, REGD_NO => $regd_no, PHONE_NUM => $phone_num, MARK => $mark, PASS_YEAR => $pass_year }; return bless $self, $class; } sub display { my ($self) = @_; if ($self) { print 'Name: ', $self->{NAME}, "\n"; print 'Age: ', $self->{AGE}, "\n"; print 'Regd no: ', $self->{REGD_NO}, "\n"; print 'Phone num: ', $self->{PHONE_NUM}, "\n"; print 'Mark: ', $self->{MARK}, "\n"; print 'Pass year: ', $self->{PASS_YEAR}, "\n"; } } } my @students; while (<DATA>) { chomp; push @students, Student->new(split /:/); } find_student('x3')->display(); sub find_student { my ($regd_no) = @_; for (@students) { return $_ if $_->{REGD_NO} eq $regd_no; } return undef; } __DATA__ A:20:x1:phone4:72:2011 B:19:x2:phone2:55:2012 C:22:x3:phone3:83:2009 D:23:x4:phone1:69:2008
Output:
17:18 >perl 578_SoPW.pl Name: C Age: 22 Regd no: x3 Phone num: phone3 Mark: 83 Pass year: 2009 17:22 >
Hope that helps,
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: How can one access all the details of a person using arrays & hash?
by supriyoch_2008 (Monk) on Mar 17, 2013 at 07:37 UTC |