Telemachus wrote:
Good morning,
Hello,
I'm using a recipe from The Perl Cookbook (11.10 for anyone browsing at
home) to produce a record structure from items in a text file. The text
file itself has a simple structure:
field:value
field:value
field:value
field:value
field:value
etc.
That is, the records are separated by a blank line and they contain
key/value pairs, joined by a colon.
The code I'm working with is this:
$/ = "";
Set paragraph mode.
while (<>) {
Read a paragraph into $_. In your example a paragraph is:
" field:value
field:value
field:value
"
my @fields = split /^([^:]+):\s*/m;
Since there are multiple lines in a paragraph they use /^/m to work on
one line at a time. That pattern splits into three fields, the field
before '([^:]+):\s*', which will be '' for the first line, the field
enclosed in parentheses '[^:]+', and the field after '([^:]+):\s*'.
shift @fields;
The first field is always empty so remove it.
push(@Array_of_Records, { map /(.*)/, @fields });
Store the fields as a hash at the end of @Array_of_Records. The filter
/(.*)/ ensures that no newlines are included in the keys or values of
the hash.
}
It works well to produce an array of hashes, and I can manipulate it from
there without trouble. However, I want to understand this section better.
First question: why does the split command produce a leading null field?
(My best guess is that the regex [^:]+ captures anything that is not a
colon, and that includes a null field?!?)
Second question: what is the map doing in the last line, and why is it
written with // delimiters? (Best guess, it is including everything from
fields within parentheses (forcing the items to be treated as a list?) and
you can't use {} because of the outer {} to create the hash reference?!?)
Sorry if this is very long. I wanted to make sure to include enough
information to make the questions clear.
Another way to the same thing would be:
$/ = "";
while (<>) {
push @Array_of_Records, { /^([^:]+):\s*(.*)/mg };
}
John
--
Perl isn't a toolbox, but a small machine shop where you
can special-order certain sorts of tools at low cost and
in short order. -- Larry Wall
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/