in reply to Re: identifying null fields in bar delimited records
in thread identifying null fields in bar delimited records

They look like this:

first||third||
alpha|beta||delta|
||c|d|
one|||four|

I'd like to print something like:
field1->1
field2->2
field3->2
field4->1

  • Comment on Re^2: identifying null fields in bar delimited records

Replies are listed 'Best First'.
Re^3: identifying null fields in bar delimited records
by wfsp (Abbot) on May 31, 2005 at 14:33 UTC
    Build a hash
    #!/usr/bin/perl use strict; use warnings; my %null; while (<DATA>){ my @fields = split(/\|/); for my $i (0..$#fields){ $null{"field$i"}++ unless $fields[$i]; } } for my $key (sort keys %null){ print "$key->$null{$key}\n"; } __DATA__ first||third|| alpha|beta||delta| ||c|d| one|||four|
    output:
    field0->1 field1->3 field2->2 field3->1
    The field numbers start at zero but also the second field has 3 compared to 2 in your desired ouput.

    The third line of your data starts with two bars, isn't that 2 null fields?

      Given that the null fields can occur at the ends of lines, your split needs to be phrased as follows (update) my first impulse would be to use split as follows (but your way certainly does work) (/update):
      my @fields = split( /\|/, $_, -1 );
      The "-1" at the end will preserve trailing null fields, so if the input always has a consistent number of field separators on every line, the number of elements assigned to @fields will always be the same. Then it's easy to just step through the array to check for undef elements.
Re^3: identifying null fields in bar delimited records
by holli (Abbot) on May 31, 2005 at 12:00 UTC
    How does "first||third||" fit together with "field1->1"? There are 3 null fields in that line.


    holli, /regexed monk/