http://qs321.pair.com?node_id=11123135


in reply to Applying regex to each line in a record.

This can also be accomplished without a regex at all, thanks to the split() function.

use strict; use warnings; use Data::Dumper; my %hash; my $header; while (my $line = <DATA>) { chomp $line; my ($k, $v) = split ':', $line; next if ! $k; if (! $v) { $header = $k; next; } $hash{$header}{$k} = $v; } print Dumper \%hash; __DATA__ first: this:that here:there when:what how:where now:later second: this:that here:there when:what how:where now:later

Output:

$VAR1 = { 'second' => { 'now' => 'later', 'how' => 'where', 'here' => 'there', 'this' => 'that', 'when' => 'what' }, 'first' => { 'when' => 'what', 'how' => 'where', 'here' => 'there', 'this' => 'that', 'now' => 'later' } };

Replies are listed 'Best First'.
Re^2: Applying regex to each line in a record.
by choroba (Archbishop) on Oct 24, 2020 at 21:46 UTC
    > without a regex at all, thanks to the split() function.

    Note that the first argument to split, even if you write it as ':', is a regex. Only a space is special.

    map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]

      I was hoping that nobody would notice and point that out ;)

      But yes, choroba is absolutely correct in his assessment.