Another way, similar to the OPed and LanX's solutions:
c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -le
"use autodie;
;;
my $file = qq{(Special)\n}
. qq{TG: VIN:1000000\n}
. qq{type: a very special type of plane\n}
. qq{\n}
. qq{(Special)\n}
. qq{TG: VIN:1000001\n}
. qq{type: a very special type of car\n}
. qq{\n}
. qq{ \t \n}
. qq{(Special)\n}
. qq{TG: VIN:1000002\n}
. qq{type: a very special type of boat\n}
;
;;
open my $fh, '<', \$file;
;;
my $rx_vin = qr{ \d+ }xms;
my $rx_text = qr{ \S (?: \s* \S+)* }xms;
;;
my %hash;
;;
local $/ = '';
while (my $block = <$fh>) {
my $extracted =
my ($vin, $text) =
$block =~ m{
\A \s* \Q(Special)\E \s+ TG: \s+ VIN: \s*
($rx_vin)
\s+ type: \s+
($rx_text)
\s* \Z
}xms;
die qq{bad block '$block'} unless $extracted;
die qq{duplicate vin '$vin'} if exists $hash{$vin};
;;
$hash{$vin} = $text;
}
;;
close $fh;
;;
dd \%hash;
"
{
1000000 => "a very special type of plane",
1000001 => "a very special type of car",
1000002 => "a very special type of boat",
}
Please note that:
-
A VIN (at least for a car) has a definite pattern that could be used to make $rx_vin quite discriminating (it's quite naive now (update: indeed, it's incorrect for an automotive VIN; don't know about boats or planes)).
-
The $rx_text regex could probably be sharpened, but I don't know just what your text looks like.
-
The whole extraction pattern is fairly tolerant of whitespace, but will die at the first "block" that doesn't look like a block, and you may not want this. (Also rejects duplicate VINs.)
Give a man a fish: <%-{-{-{-<
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.