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

holli++

Here's a humble for loop:

#!/usr/bin/perl use strict; use warnings; my $line = "a||c|\t| |d||e"; my @fields = split(/\|/, $line); my @null; for my $i (0..$#fields){ push @null, $i unless $fields[$i]; } print "null fields: ", scalar @null, "\n"; print "at field: "; print ++$_, ", " for @null; # output # null fields: 2 # at field: 2, 7,

Replies are listed 'Best First'.
Re^3: identifying null fields in bar delimited records
by lupey (Monk) on May 31, 2005 at 12:38 UTC
    holli and wfsp, great answers. Now, I'd like to make this snippet of code more general by turning the delimiter into a variable. But doing so doesn't work (I'm struggling to understand regular expressions).
    my $delim = '|'; my $line = "a||c|\t| |d||e"; my @fields = split(/\\$delim/, $line); # output # null fields: 0 # at field:
      my $delim = qr/\|/; my $line = "a||c|\t| |d||e"; my @fields = split($delim, $line);

      The qr operator quotes and compiles its STRING as a regular expression.
      split splits on a pattern (regex).

      update:

      Added explanation.

      I would put the escaping backslash into $delim, so you are truly independent. Besides that your code works fine and splits the string as intended.
      my ($delim, $line, @fields); $delim = '\|'; $line = "a|c||b"; @fields = split(/$delim/, $line); print join ("*", @fields), "\n"; $delim = ';'; $line = "a;c;;b"; @fields = split(/$delim/, $line); print join ("*", @fields), "\n"; #a*c**b #a*c**b
      What else did you expect?


      holli, /regexed monk/
Re^3: identifying null fields in bar delimited records
by jjohhn (Scribe) on May 31, 2005 at 14:04 UTC
    I posted as anon by mistake, which means I can't edit my post to remove the superfluous line containing the variable "line".