#!/usr/bin/perl
use warnings;
use strict;
#the text could be from a file, etc. but:
my $text;
undef $/;
$text = <DATA>;
#The keys would be known, e.g.
my @keys = (
'A key could be:',
'A value could be:',
'The order is:',
'The keys are:',
);
#What I'd like to end up with is something like:
my %result = (
'A key could be:' => 'Anything\n\n',
'A value could be:' => 'Any text.\n\nEven multiple lines.\n\nMight include a : or whatever\n\n',
'The order is:' => '\nunpredictable\n\n',
'The keys are:' => 'optional\n',
);
#the code below works but seems inefficient:
my %mess;
foreach my $key(@keys) {
if ($text =~ /$key/) {
$mess{$key} = {'remainder' => $', 'length' => length $'};
}
}
while (my ($mess_key, $mess_val_ref) = each %mess) {
foreach my $key(@keys) {
if ($mess_val_ref->{'remainder'} =~ /$key/) {
my $length = length $`;
if ($length < $mess{$mess_key}{'length'}) {
$mess{$mess_key}{'length'} = $length;
$mess{$mess_key}{'value'} = $`;
}
}
else {
$mess{$mess_key}{'value'} = $mess_val_ref->{'remainder'};
}
}
}
while( my($key, $val) = each %mess ) {
print $key, $val->{'value'};
}
#other ideas?
__DATA__
A key could be: Anything
A value could be: Any text.
Even multiple lines.
Might include a : or whatever
The order is:
unpredictable
The keys are: optional