in reply to Re^4: Perl Formatting Text
in thread Perl Formatting Text
You need something like this:
Then instead of just print "whatever" you just put in print OUT "whatever" . The print goes to the OUT file instead of to the terminal.open OUT , '>', "outfilename" or die "unable to open out $!";
The kind of problem that you are having where the file contains something weird that you find during debug happens all the time when using ad hoc methods to parse something for which a complete spec is not known in advance.
I am happy to see that you are making an effort to understand the code. My efforts to help are pointless unless actual knowledge is being transferred.
The generic problem is that you can't output the new lines until you are sure that you've got all of the referencedesignators. The typical solution is to delay the printout until you have seen the next line with a valid $netname. This introduces a couple of complications.
First, how do we tell if this is a new "record" or a continuation of the previous line? That depends upon what $netnames look like. If all netnames have an underscore in them and the other continuation tokens do not, then something like this would work:
The above code decides that "10GBE_" is a match. If that regex (regular expression) is not adequate, then some other "rule" is needed.my $test = '10GBE_ADDR1'; #decide if first part of line has ABC901X_ ... print "new record\n" if $test =~ m/^[A-Z0-9a-z]+_/;
Second, since we don't have a simple: read line, process line, print line(s), some "memory" is needed. ie. we have "read line, print lines based upon previous $netname and previous @singlereference if a new record is starting, process line".
Third, you will find that the last record is problematic. The while loop will end when there are no more lines, but that last record will not have been output yet. So you need some "cleanup" code to do that.
Now you can call this subroutine inside or after the while loop ends provided that you give @singlereference and $netname greater scope by declaring them before the while loop starts.sub print_record { return unless @singlereference; #no work to do @singlereference = sort {$a <=> $b} @singlereference; foreach my $col (@singlereference) { print "$netname $col\n"; } @singlereference =(); #reset array to empty return; }
Hope these tips helps. Try some code and ask if you are having problems. The code doesn't need to some "masterpiece", it just has to be logically correct and work.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^6: Perl Formatting Text
by oopl1999 (Novice) on Jun 25, 2016 at 01:43 UTC | |
by Marshall (Canon) on Jun 26, 2016 at 14:26 UTC |