Consider using XML::Twig instead of regexes to process the file. Easier to apply changes to a data element before creating the flat file rather a complete line afterwards.
poj#!/usr/bin/perl use strict; use XML::Twig; my $xml = join '',<DATA>; my $twig = XML::Twig->new( twig_handlers => {'datafield' => \&datafield} ); $twig->parse( $xml ); sub datafield { my( $t, $e ) = @_; my %subfield = (); for my $elem ($e->children('subfield')){ $subfield{$elem->att('code')} = $elem->text; } my @f = (); $f[0] = $e->att('tag'); $f[1] = $e->att('ind1').$e->att('ind2'); my @tmp; for (sort keys %subfield){ push @tmp,$_.$subfield{$_}; } $f[2] = join '|',@tmp; # change if ($subfield{'x'} =~ /^(isbn13|isbn)$/){ $f[0] =~ s/024/020/; } # flat format for output printf ".%s. %s|%s\n",@f if ($f[2]); # skip blanks } #.245. 14|aThe solar system|cChris Oxlade [Author] #.024. 3#|a9780750247092|xisbn13 #.024. 3#|a0750247096|xisbn __DATA__ <collection> <record> <datafield ind1="1" ind2="4" tag="245"> <subfield code="a">The solar system</subfield> <subfield code="c">Chris Oxlade [Author]</subfield> </datafield> </record> <record> <datafield ind1="3" ind2="#" tag="024"> <subfield code="a">a9780750247092</subfield> <subfield code="x">isbn13</subfield> </datafield> <record> </record> <datafield ind1="3" ind2="#" tag="024"> <subfield code="a">a0750247096</subfield> <subfield code="x">isbn</subfield> </datafield> </record> <record> <datafield ind1="3" ind2="#" tag="024"> </datafield> </record> </collection>
In reply to Re^2: Remove line and modify another
by poj
in thread Remove line and modify another
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |