SPUG: reg exp's

Yitzchak Scott-Thoennes sthoenna at efn.org
Thu Sep 5 16:21:19 CDT 2002


On Wed, 4 Sep 2002 20:30:29 -0700 , Ryan.Parr at wwireless.com wrote:
>Ok, gotta add my two cents. Some of the other solutions won't work because
>heading1 in group one will get overwritten by heading 1 in group 2 and then
>on to three etc.

I didn't see any that did that.

>In my opinion the best data structure for this situation would be an array
>of hash refs. Each hash ref is it's own group. Each group is terminated in
>the file by a single blank line.
>
>So here's my code. This will even make sure that multiple newlines between
>groups or at the end of the file won't cause multiple hasrefs with the
>single key 'undef' :)

Or that.  Though yours gives an empty hashref if there are leading empty
lines.

>#!/usr/bin/perl
>use strict;

missing "use warnings" here.

>while(chomp($_ = <IN>)) {

With warnings enabled, you get a warning on the chomp.
Put the chomp in the body:    while (<IN>) { chomp;

>        if(/^\s*$/) {
>                $last_is_blank = 1;
>                next;
>        }
>
>        my($key,$val) = split(/:\s/);
>        if($last_is_blank) {
>                push @shiznit,{ $key => $val };
>        }
>        else {
>                $shiznit[$#shiznit]->{$key} = $val;
>        }
>        $last_is_blank = 0;
>}

Other than that, yours does pretty much the same as mine:

my $data;
$/ = '';  # read in a paragraph at a time
while (<DATA>) {
    push @$data, { split /:\s*(.*)\n+/ }
}

though for non-quick&dirty use I'd do something more like yours
with user warning messages for bad data.

 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
     POST TO: spug-list at pm.org       PROBLEMS: owner-spug-list at pm.org
      Subscriptions; Email to majordomo at pm.org:  ACTION  LIST  EMAIL
  Replace ACTION by subscribe or unsubscribe, EMAIL by your Email-address
 For daily traffic, use spug-list for LIST ;  for weekly, spug-list-digest
     Seattle Perl Users Group (SPUG) Home Page: http://seattleperl.org




More information about the spug-list mailing list