1: This probably doesn't present much of a challenge, but I thought I'd post 
   2: it since it's the first time I've ever really grokked Perl golf.
   3: 
   4: A coworker (non-programmer) has been taking a course in C and asked me to 
   5: help out with a program that takes a list of names through input, and 
   6: print them back out when finished.  Since I don't know C, I thought I'd 
   7: show her how it could be done in Perl.  Then something weird clicked in 
   8: my brain, and I began shaving my original script down, character by 
   9: character, from 201 characters (formatted and commented) to 77.
  10: 
  11: My version takes a list of names in 'first m last' (e.g. "Larry J Wall") 
  12: format, and appends the name to a file in 'last first m' format.  
  13: The script ends when it does not receive input in the correct format.
  14: 
  15: Here's what I came up with...
  16: 
  17: 
  18: #!/usr/bin/perl
  19: 
  20: open(N,">>names");while(<>){last if!/(\w+) (\w) (\w+)/;print N"$3\t$1\t$2\n"}
  21: 
  22: 
  23: It can be brought down to 71 characters by shortening the filename 
  24: and replacing the tabs with spaces, but I thought I'd go for an output 
  25: with a tad bit of formatting.  :)
  26: 
  27: joecamel

Replies are listed 'Best First'.
Re: A first one-liner
by MeowChow (Vicar) on Jul 12, 2001 at 10:52 UTC
    Here's a one-liner that will do much the same thing:
    perl -pale '$_=join"\t",@F[2,0,1]'
    Or, to match the behaviour more closely:
    perl -pale '$_=join"\t",@F[2,0,1];@F^3&&last' >> OUTFILE INFILE
       MeowChow                                   
                   s aamecha.s a..a\u$&owag.print
Re: A first one-liner
by MZSanford (Curate) on Jul 12, 2001 at 20:28 UTC
    The following is untested, but still pretty cool.
    perl -ne 'BEGIN {open(N,">>names")};/(\w+) (\w) (\w+)/ || exit;print N + "$3\t$1\t$2"'

    Calm begets calm