I always try to find some sort of reliable landmark in the format I'm reading and use it to disambiguate other parts of the "markup" on a syntatictal level, rather than going into the semantics (like "does the sum of tags I have here constitue a complete DN yet?" as BrowserUk did).
In this case the (almost) reliable landmark is the commas separating the tags. If we read the file from comma to comma, there is only one ambiguous case: we can read across the newline that separates the tag at the end of one DN from that which begins the other DN. This is the one case we need to care about. How can we unambiguously conclude that is what the newline at hand means? If and only if the newline is followed by \w+=.
local $/ = ","; my $dn = ""; while(<>) { my $complete_dn; if(m/ \A (.+) \n ( \w+ = .+ ,) \z /sx) { $complete_dn = $dn . $1; $dn = $2; } else { $dn .= $_; } if($_ = $complete_dn) { s/\n+//g; do_whatever_with($_); } }
Update: This doesn't quite work. / \n \w+ = /x is not strong enough - what happens if it's the tag itself that's broken up? Then we get a dangling beginning of the tag as the end of the current DN and the rest of the tag with equals sign and value, newline and the second tag as the beginning of the new DN. However, since we read from comma to comma, we can garantuee that we always get the beginning of a tag at the start of the string. Therefor requiring that an equals sign precede the newline clarifies this corner case:
local $/ = ","; my $dn = ""; while(<>) { my $complete_dn; if(m/ \A (.+ = .+) \n ( \w+ = .+ ,) \z /sx) { $complete_dn = $dn . $1; $dn = $2; } else { $dn .= $_; } if($_ = $complete_dn) { s/\n+//g; print $_, "\n"; } }
Here's my "test suite":
I piped this script's output into the other to test it.#!/usr/bin/perl -w use strict; undef $/; my $data = <DATA>; my @munged = ($data) x length $data; substr $munged[$_], $_, 0, "\n" for 0 .. $#munged; print @munged; __END__ cn=Perl Monks,ou=Dining Hall,ou=Monastery,c=Universe
Makeshifts last the longest.
In reply to Re: Match a string that can contain a carriage return in a random position.
by Aristotle
in thread Match a string that can contain a carriage return in a random position.
by robartes
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |