arajani has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,

I'm reading a file (each line has many fields enclosed by
double quotes). I want to count the number of double quotes
in each line. The fields are separated by commas(,) but I
cannot use this as separator as field also may have the
comma as part of its string. So to cross check the number
of fields in a record (line) I am counting the number of
double quotes. So far good. I have the following code,
which is hanging. Syntax seem to be ok, but still this is
a problem. Any suggestions ?
open(FILENAME,"c:\\abc.txt") || die "Cannot Open the file.\n" ; my $quote_count = 0 ; my $pos = 0 ; my $record = "" ; while(<FILENAME>) { $record = $_ ; chomp $record ; while ($pos = index($record, '"', $pos) != -1) { $quote_count++; $pos++; } } print "Number of double quotes are $quote_count\n"; close FILENAME ;
The file abc.txt has following data (just 2 lines)
"11111","xxxx","yyyy","222, world drive"
"22222","abc","jkl","my road, my world"
What is causing the hanging of the process ? pls let me know.

Thanks in advance,

Raj.

Replies are listed 'Best First'.
Re: Counting number of double quotes in a string
by japhy (Canon) on May 10, 2002 at 22:26 UTC
    It's a problem with precedence:
    friday:~ $ perl -MO=Deparse,-p -e '1 while $x = $y != $z' -e syntax OK '???' while ($x = ($y != $z));
    As you can see, you're doing $pos = (index() != -1), where you want to do ($pos = index()) != -1. This problem causes $pos to be 1 all the time!

    I have a better idea. Use the tr/// operator. $count += tr/"// while <FILE>;

    _____________________________________________________
    Jeff[japhy]Pinyan: Perl, regex, and perl hacker, who'd like a job (NYC-area)
    s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;

      Hi Japhy,

      I realised the folly of not careful about the precedence.
      Thanks a lot and appreciate the help.

      Regards,

      Raj.
Re: Counting number of double quotes in a string
by thelenm (Vicar) on May 10, 2002 at 22:23 UTC
    You will probably want to check out the Text::CSV_XS module, which can do parsing of CSV files for you and will make your life a lot easier.

    But to answer your question directly, to count the number of double-quote characters in a line, do this:

    $count = ($line =~ y/"//);
Re: Counting number of double quotes in a string
by mephit (Scribe) on May 11, 2002 at 03:28 UTC
    Like I suggested in reply to this question, Text::Parsewords might do the trick. I've never used the CSV module mentioned in another reply, so I wouldn't know how to go about using it to solve this problem, but it should be possible with ParseWords.