Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: regex problem

by johngg (Canon)
on Mar 05, 2018 at 00:43 UTC ( #1210328=note: print w/replies, xml ) Need Help??


in reply to regex problem

A solution using splits and maps to build a hash. The order of the output might be problematic if you desire something other than sorted.

johngg@shiraz ~/perl/Monks $ perl -Mstrict -Mwarnings -E ' open my $inFH, q{<}, \ <<EOD or die $!; abcd 723-724 abcde 552-554-553 abcdef 756 EOD my %hash = map { $_->[ 0 ] => [ split m{-}, $_->[ 1 ] ] } map { [ split ] } <$inFH>; foreach my $key ( sort keys %hash ) { say qq{$key $_} for @{ $hash{ $key } }; }' abcd 723 abcd 724 abcde 552 abcde 554 abcde 553 abcdef 756

I hope this is useful.

Update: This version dispenses with the hash so items will be output in the same order as input.

johngg@shiraz ~/perl/Monks $ perl -Mstrict -Mwarnings -E ' open my $inFH, q{<}, \ <<EOD or die $!; abcd 723-724 abcde 552-554-553 abcdef 756 EOD say qq{@$_} for map { my $key = $_->[ 0 ]; my @nos = split m{-}, $_->[ 1 ]; map { [ $key => shift @nos ] } 1 .. scalar @nos; } map { [ split ] } <$inFH>;' abcd 723 abcd 724 abcde 552 abcde 554 abcde 553 abcdef 756

Update 2: Even simpler.

johngg@shiraz ~/perl/Monks $ perl -Mstrict -Mwarnings -E ' open my $inFH, q{<}, \ <<EOD or die $!; abcd 723-724 abcde 552-554-553 abcdef 756 EOD say qq{@$_} for map { my( $key, $rest ) = split; my @nos = split m{-}, $rest; map { [ $key => shift @nos ] } 1 .. scalar @nos; } <$inFH>;' abcd 723 abcd 724 abcde 552 abcde 554 abcde 553 abcdef 756

Cheers,

JohnGG

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (8)
As of 2018-11-14 19:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My code is most likely broken because:
















    Results (177 votes). Check out past polls.

    Notices?