CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner: Re: [lilmark] Moving part of Multi-Dimensional Array to an Array: Edit Log



7stud
Enthusiast

Dec 27, 2012, 4:13 PM


Views: 2131
Re: [lilmark] Moving part of Multi-Dimensional Array to an Array


Code
 
use strict;
use warnings;
use 5.012;

my %results;

while ( my $line = <DATA> ) {
chomp $line;

my @pieces = split ' ', $line; #splits on any group of whitespace
my $key = $pieces[3];

push @{ $results{$key} }, $line;

}

use Data::Dumper;
say Dumper \%results;


for my $key (sort keys %results) {
my @lines = @{ $results{$key} };

for (sort @lines) {
say;
}
say "*" x 20;
}


__DATA__
201211 b c 2 a
201203 y z 1 x
201201 bb cc 2 aa
201210 yy zz 1 xx


Code
--output:-- 
$VAR1 = {
'1' => [
'201203 y z 1 x',
'201210 yy zz 1 xx'
],
'2' => [
'201211 b c 2 a',
'201201 bb cc 2 aa'
]
};


201203 y z 1 x
201210 yy zz 1 xx
********************
201201 bb cc 2 aa
201211 b c 2 a
********************


By storing references, you can avoid calling split twice(although at the cost of more complexity):


Code
use strict; 
use warnings;
use 5.012;

my %results;

while ( my $line = <DATA> ) {
chomp $line;

my @pieces = split ' ', $line;
my $key = $pieces[3];

push @{ $results{$key} }, \@pieces;

}

use Data::Dumper;
say Dumper \%results;

for my $key (sort keys %results) {
my $AoA = $results{$key};
my @ordered_refs = sort { @$a[0] cmp @$b[0] } @$AoA;

for my $ref (@ordered_refs) {
say "@$ref";
}
say "*" x 20;
}

__DATA__
201211 b c 2 a
201203 y z 1 x
201201 bb cc 2 aa
201210 yy zz 1 xx



Code
--output:-- 
$VAR1 = {
'1' => [
[
'201203',
'y',
'z',
'1',
'x'
],
[
'201210',
'yy',
'zz',
'1',
'xx'
]
],
'2' => [
[
'201211',
'b',
'c',
'2',
'a'
],
[
'201201',
'bb',
'cc',
'2',
'aa'
]
]
};

201203 y z 1 x
201210 yy zz 1 xx
********************
201201 bb cc 2 aa
201211 b c 2 a
********************



(This post was edited by 7stud on Dec 27, 2012, 5:28 PM)


Edit Log:
Post edited by 7stud (Enthusiast) on Dec 27, 2012, 4:16 PM
Post edited by 7stud (Enthusiast) on Dec 27, 2012, 4:17 PM
Post edited by 7stud (Enthusiast) on Dec 27, 2012, 4:17 PM
Post edited by 7stud (Enthusiast) on Dec 27, 2012, 4:17 PM
Post edited by 7stud (Enthusiast) on Dec 27, 2012, 4:56 PM
Post edited by 7stud (Enthusiast) on Dec 27, 2012, 5:08 PM
Post edited by 7stud (Enthusiast) on Dec 27, 2012, 5:09 PM
Post edited by 7stud (Enthusiast) on Dec 27, 2012, 5:24 PM
Post edited by 7stud (Enthusiast) on Dec 27, 2012, 5:25 PM
Post edited by 7stud (Enthusiast) on Dec 27, 2012, 5:28 PM


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives