in reply to Reading Text File into Hash to Parse and Sort

Consider loading your data into a hash-of-hashes structure:
use warnings; use strict; my %data; <DATA>; # Discard header while (<DATA>) { chomp; my ($tick, @cols) = split /\s*\|\s*/; my %comp; @comp{qw(name price cap ind)} = @cols; $data{$tick} = { %comp }; } use Data::Dumper; $Data::Dumper::Sortkeys=1; print Dumper(\%data); __DATA__ TICKER| CO. NAME| PRICE| MARKET CAP| INDUSTRY ABC | ABC Co.| 15.5| 5000| Industrials AB | Alpha Beta| 12| 2500| Materials DOZ | ZZZZZ| 5.05| 2800| Telecom DX | DX Co.| 77.2| 12000| Industrials DXX | DXX Co.| 50.25| 9000| Utilities

Prints:

$VAR1 = { 'AB' => { 'cap' => '2500', 'ind' => 'Materials', 'name' => 'Alpha Beta', 'price' => '12' }, 'ABC' => { 'cap' => '5000', 'ind' => 'Industrials', 'name' => 'ABC Co.', 'price' => '15.5' }, 'DOZ' => { 'cap' => '2800', 'ind' => 'Telecom', 'name' => 'ZZZZZ', 'price' => '5.05' }, 'DX' => { 'cap' => '12000', 'ind' => 'Industrials', 'name' => 'DX Co.', 'price' => '77.2' }, 'DXX' => { 'cap' => '9000', 'ind' => 'Utilities', 'name' => 'DXX Co.', 'price' => '50.25' } };

Refer to perldsc. You need to decide how to manipulate it from there.

Replies are listed 'Best First'.
Re^2: Reading Text File into Hash to Parse and Sort
by SimonPratt (Friar) on Apr 22, 2015 at 08:30 UTC

    Not bad. I would change the way the keys are generated slightly, though. This change allows the data vendor to do weird things, like change the order of headers or add / remove columns without affecting your underlying process (unless they completely balls it up).

    my %item_map = ( 'CO.NAME' => 'name', 'MARKETCAP' => 'cap', 'INDUSTRY' => 'ind' ); chomp(my $headers = <DATA>); my @headers = map {s/\s//g; ($item_map{$_} || lc $_)} split /\s*\|\s*/ +, $headers;

    Yes, purists may point out that this is serious over-engineering. I would retort that if they had to maintain loading filesets from a couple of hundred different FTSE feeds they might rethink their position (though to be fair, FTSE are a lot better these days)