in reply to golf: shortest way to parse a pipe delimited file

perl -MData::Dumper -lanF'\|' -e '$p{$F[0]}=[@F[1..$#F]]}END{print Dum +per \%p' abcd
Where abcd has your data.

Assuming standard golfing rules where you give the body of a function that takes whatever parameters are useful:

#!/usr/bin/perl my %p; sub func { my($x,@x)=$_[0]=~/([^\|\n]+)/g;$p{$x}=\@x # Or ... chomp(my($x,@x)=split'\|',pop);$p{$x}=\@x } open SRC, 'abcd'; while (<SRC>) { func($_); } use Data::Dumper; print Dumper \%p;
Either way, I'm at 41 characters

My criteria for good software:
  1. Does it work?
  2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?

Replies are listed 'Best First'.
Re^2: golf: shortest way to parse a pipe delimited file
by tilly (Archbishop) on Nov 10, 2005 at 15:36 UTC
    Your first solution will misbehave if you run across a line like:
    foo||bar
    Your second solution can be shortened by 3 characters:
    sub func { #23456789_123456789_123456789_12345678 chomp(@_=split'\|',pop);$p{+shift}=\@_ }
    and one more if you're willing to replace chomp with chop.
      this fails by giving an empty hash entry.
      $VAR1 = { '' => [], 'aaa' => [ 'bbb', 'ccc' ], 'foo' => [ 'bar', 'baz' ] };
        It doesn't fail for me with Perl 5.8.7.

        My best guess is that your input had a blank line in it at the start or the end. That blank line would (legitimately from the spec) result in the output that you saw.

Re^2: golf: shortest way to parse a pipe delimited file
by bageler (Hermit) on Nov 10, 2005 at 19:42 UTC
    I see more than 41 characters because you say while (<SRC>) { } In my solution, the filehandle is part of the solution character count. If I put my solution in the context of yours it looks like this:
    sub parse{ #12345678901234567890123456789012345678901234567890 %p=map{chomp;split/\|/;shift@_,[@_]}@_ } parse(<SRC>);
    and is 37 characters.
      Save a couple of chars by taking advantage of the fact that shift defaults to @_ while in a sub.
      %p=map{chomp;split/\|/;shift,[@_]}@_
      Using chop instead of chomp would help, but might not be portable.

      Caution: Contents may have been coded under pressure.