Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: Applying regex to each line in a record.

by stevieb (Canon)
on Oct 24, 2020 at 20:56 UTC ( [id://11123135]=note: print w/replies, xml ) Need Help??


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 (Cardinal) 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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11123135]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (5)
As of 2024-04-25 10:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found