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

I am trying to parse some cddb files that i have laying around with perl, but unfortunately, the script i wrote only picks up every other line. Why is this?
#!/usr/bin/perl -w ##base16's cddb script %title=(); sysopen(FILEDATA, "$ARGV[0]", O_RDWR) or die "no input"; flock(FILEDATA, 2); while (<FILEDATA>) { $match = <FILEDATA>; if ($match =~ /^TTITLE(\d+)=(.+)$/) { $title{$1} = $2; } } while ( ($key, $value) = each %title) { print $key, '-', $value, "\n"; } close(FILEDATA);

Replies are listed 'Best First'.
RE: regexps and hashes
by lhoward (Vicar) on May 15, 2000 at 21:44 UTC
    Your problem is with this piece of code....
    while (<FILEDATA>) { $match = <FILEDATA>; if ($match =~ /^TTITLE(\d+)=(.+)$/) { $title{$1} = $2; } }
    change it to
    while (<FILEDATA>) { $match = $_; if ($match =~ /^TTITLE(\d+)=(.+)$/) { $title{$1} = $2; } }
    and it should work properly. Your 2 calls to <FILEDATA> are causing 2 reads to happen, making it skip every other line (as you discovered).
      or simply
      while (<FILEDATA>){ if (/^TTITLE(\d+)=(.+)$/) { $title{$1} = $2; } }
      Sweet! thanks. This is why i love perlmonks.org....
RE: regexps and hashes
by turnstep (Parson) on May 16, 2000 at 19:15 UTC
    Also note that since you put everything into a hash and then extract it, the order your script outputs will most likely NOT be the same as the order in the original file. Try something like this to smooth things out:
    while (<FILEDATA>) { /$TTITLE(\d+)=(.+)$/ and print "$1-$2\n"; }
    or if you need to save them for later use:
    while (<FILEDATA>) { /$TTITLE(\d+)=(.+)$/ and push(@titles, "$1=$2\n"); } ## Then just: print @titles;

    These ways also allow more than one TTITLE of the same number to exist, if that's a factor. A hash will only save the value of the last one read.