[PLUG] Perl strategies for parsing multi-line configs

Colin Kuskie ckuskie at dalsemi.com
Fri Mar 19 09:01:02 UTC 2004


On Thu, Mar 18, 2004 at 02:34:54PM -0800, Stafford A. Rau wrote:
> I often have to compile information from things like Cisco configs, and
> I'm hoping for some suggestions to deal with this in a more elegant
> fashion than my normal mess of "if (/^interface/) { ...blah...; }".
> 
> Here is part of a typical config:
> 
> interface FastEthernet0/16
> !
> interface FastEthernet0/17
>  description cubicle x
> !
> interface FastEthernet0/18
>  description Company CEO laptop
>  duplex full
>  speed 100
>  switchport access vlan 152
> !
> interface FastEthernet0/19
>  description Crappy Server
>  switchport access vlan 51
> !
> interface FastEthernet0/20
> !
> 
> So each interface is the basic unit I'm working with, but there are a
> variable number of items that follow each interface.
> 
> If I want to make a list of, for instance, interface, vlan, and
> description, is there a cleaner way to do it rather than testing for
> '/^interface/' and setting $description to empty and $vlan to 1 (the
> default) each time I hit a new interface line?
> 
> What I would really like to get are generalized strategies for reading
> multi-line, variable-length text records.

The previous reply is right, look into Parse::RecDescent.  But
for this particular case, there is a very good, very simple
core Perl solution:

Each record is delimited by \n!\n.
Each element appears to be line delimited (\n)

So this should work:

#!/usr/bin/perl -w

use strict;

$/ = "\n!\n"; ##Input line delimiter set to record delimiter

while (<>) {
  my @fields = split "\n";
}

Now it's up to you to parse each element.

Colin




More information about the PLUG mailing list