G'day matthew_t_dooley,
Welcome to the Monastery.
"Is this very ugly? Is there a more elegant way to do it?"
This is somewhat "ugly" and certainly could be made "more elegant";
however, there are issues with your code that go beyond its beauty.
"I want to process each "H00".."D99" block at a time and have used $/="\nH00"
When changing a special variable (such as $/), you should use local in an anonymous block. See "Localization of special variables".
"In order to extract the "H01" records from this set, I have used ..."
Here you've hard-coded the literal 'H01' in two places.
In general, this is a bad idea.
Multiple, hard-coded literals increase the chances of introducing a typo, without introducing a syntax error which Perl could tell you about, potentially causing bugs which are hard to track down.
Additionally, if you need to change this literal (perhaps as part of some future code enhancement), you'll need to make multiple, identical changes: more work for you and more chances of introducing errors.
Beyond the actual code issues, there's some problems with your post.
My intention here is not to berate you but rather just point out the issues.
-
A prosaic description of your data is rarely helpful.
A small, representative example is much better: we can see exactly what the data looks like and we can use it directly in any code samples we provide to you.
At the time of writing this, I see two monks have made (different) guesses as to your data and, in my code example below, I've made a third. Are any of us right?
-
You provide no context for the few lines of code you've shown.
There might be a much better way to write your code but, again, you've left us guessing.
A short, working example (with the output it produces - where appropriate), greatly increases your chances of getting (more) helpful answers from us: which would be why you spent the time to post your question here in the first place.
-
The markup was fixed before I first viewed your post.
Few monks, myself included, will bother to answer posts that are illegible: we're happy to respond to questions but less happy if we have to rewrite the question first.
These guidelines should help you with any future posts.
Here's my take on a better way to write the code:
#!/usr/bin/env perl -l
use strict;
use warnings;
{
local $/ = "\nH00";
while (<DATA>) {
my ($h01) = / ^ ( H01 .* ) $ /mx;
if (substr($h01, 14, 2) eq 'SA') {
print 'WANTED: ', $h01;
}
}
}
__DATA__
H00... don't care ...
H01... block1 SA ...
D01... don't care ...
H00... don't care ...
H01... block2 SX ...
D01... don't care ...
H00... don't care ...
H01... block3 SA ...
D01... don't care ...
Output:
$ pm_1128584_process_edi_file.pl
WANTED: H01... block1 SA ...
WANTED: H01... block3 SA ...
For difficulties with the regular expression I've used, see perlre.
Specifics of the modifiers (/.../mx) can be found in the Modifiers section of that document.
|