Telemachus wrote:
On Mon Nov 17 2008 @ 10:21, John W. Krahn wrote:
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.

Thanks for your careful explanation. I was just in the process of writing
that I had worked out that the map keeps newlines out. I'll push my luck
and ask two further questions. First, what exactly is the "null field" at
the start of my first line, or where does it come from?

split always (unless the third argument is 1) splits into at least two fields. If you have the string $x = ':' then split( /:/, $x, -1 ) will return the two strings '' and '' (zero length strings).


In the version you
wrote of my data, you visualized it with a space,

*NO*, I did not use a space, that was two quotes with nothing in between.


but it's not (normally)
visible.  (This may just be something very simple about computers and how
they represent text that I don't know.) Second, if I know that my records only have newlines at the end of lines is there any larger advantage to using the map construct above instead of simply chomp @fields?

TIMTOWTDI  See my example at the end of the post.

chomp() removes the value of the $/ variable and since the value of the $/ variable was changed in the example it wouldn't do what you expected for chomp @fields.


(One
advantage of chomp for me is that I'm in no danger of misunderstanding it
later.)



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/


Reply via email to