J.Carter J.Carter - 1 year ago 60
Perl Question

What changes in the loop needed to get the output?

I have files that has header format starts with > character. Say if the header is in this format: '>anything1|anything2', I use this script to trim header and to get output header '>anything1'.

while (<>) {
if (/^(>[^|]*)/) {
print "$1\n";
} else {

But now, in my files some header are large like this:

>anything1|anything2|anything3 bla bla bla /#

and some headers are like:


Now from this mixed header type in a single file, if I want a output that trim headers up to 2 character for larger headers (that is, '>anything1|anything2' for the above large header) and keep one character for the small headers (i.e., '>anything1' only for the above small header), what changes should I have to do in my loop?


Answer Source

How about getting out of that regex

while (<>) 
    if (/^>/) 
        my @fields = split '\|', $_;

        if (@fields <= 2) {  print $fields[0] }
        else              {  print join '|', @fields[0,1] }



Please consider possible edge cases. It's easy when you have an array.

With regex, one can match cases separately, or carefully come up with one that somehow bundles those two to three different scenarios, which will be far more involved.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download