The pattern match in the above assumes that the 3rd and 4th fields (not sure what they are) are always just two characters long, and everything between the ID and the 3rd field is the student name. It gives the following output:#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my $sdata = 'student.data'; my %students; open my $infile, '<', $sdata or die "Cannot open $sdata:$!\n"; while (my $line = <$infile>) { chomp($line); my ($id,$name,$f3,$f4) = $line =~ m/^(\d+)\s(.*)\s(..)\s(..)$/; $students{$name}{id} = $id; $students{$name}{f3} = $f3; $students{$name}{f4} = $f4; } close $infile; print Dumper(\%students);
If you wanted to then print a list of students, sorted by say, ID, then you could do something like:$VAR1 = { 'Smith Tom' => { 'f3' => 'RM', 'id' => '777666555', 'f4' => 'So' }, 'Johnson Lee' => { 'f3' => 'IE', 'id' => '555444333', 'f4' => 'Sr' }, 'Jones Mary' => { 'f3' => 'SD', 'id' => '111222333', 'f4' => 'Fr' } };
Hope this helps,for my $student (sort {$students{$a}{id} <=> $students{$b}{id}} keys % +students) { print "$student => $students{$student}{id}\n"; }
In reply to Re: Hashes with multiple values?
by McDarren
in thread Hashes with multiple values?
by MyaEsp
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |