SPUG: reg exp's

Parr, Ryan Ryan.Parr at wwireless.com
Wed Sep 4 22:30:29 CDT 2002


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.

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' :)

--BEGIN--
#!/usr/bin/perl

use strict;
use Data::Dumper qw(Dumper);

$ARGV[0] or die "Usage: $0 /path/to/data/file\n";
open(IN,$ARGV[0]) or die "Couldn't open $ARGV[0]: $!\n";

my @shiznit = ({}); # Make sure to initialize since we work on upper
boundary
my $last_is_blank = 0;
while(chomp($_ = <IN>)) {
        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;
}

print Dumper(\@shiznit);
--END--

-- Ryan Parr

-----Original Message-----
From: Baker, Stephen M [mailto:stephen.m.baker at intel.com]
Sent: Tuesday, September 03, 2002 10:36 AM
To: 'spug-list at pm.org'
Subject: SPUG: reg exp's



I need to parse quickly through a file of the following format:

heading1: data1.1
heading2: data2.1
heading3: data3.1

heading1: data1.2
heading2: data2.2
heading3: data3.2

heading1: data1.3
heading2: data2.3
heading3: data3.3

to populate a data structure.  Is regular expressions the way to go about
this? OR does somebody have a trick for how this might be done?


 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
     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

 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
     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