[kw-pm] Last night's meeting

John Macdonald john at perlwolf.com
Fri Jun 19 07:56:48 PDT 2009


On Fri, Jun 19, 2009 at 08:50:58AM -0400, Raymond wrote:
> (Replying to all this time, oops)
> 
> >From the above:
> 
>  $ perl -ne'rand++$n<1?$s=$_:1;END{print$s}' <alpha.html
> 
> No need to increment a counter like $n, just use $. which gives the
> line number 1 indexed.
> 
>  $ perl -ne'rand$.<1?$a=$_:1;END{print$a}' <alpha.html
> 
> Also replaced $s with $a so it runs safe under 'warnings'. ;) Two more
> characters saved.

Neat.  And yet, 4 more chars can still be removed:

$ perl -ne'rand$.<1?$a=$_:1}{print$a' <alpha.html

This is using trickery on the internal expansion of the -n
flag, to allow us to remove the END, its braces, and its
preceeding semi-colon.

The -n provides a wrapper like:

	while(<>) {
	    # -e arg goes here
	}

The }{ in my new -e makes that end up as (blanks for readability
inserted):

	while(<>) {
	    rand $. < 1
		? $a = $_
		: 1
	}
	{
	    print $a
	}

Down to 25 chars.

Unfortunately, while perl 5.10 provides "say" as an alternative
to "print", that 2 char saving is overwhelmed by having to
enable it with "use feature qw(say);"

I'd consider it cheating to provide the "use feature qw(say)"
using the -M switch, since if the contents of a -M switch
doesn't get included in the char count you could just stick
the whole program there.  E.g.:

	$ perl -M'warnings;print"hi\n";' -pe '' </dev/null
	hi

is a zero char script to print hi under such rules, and it could
do much more complicated things with those same 0 chars, using the
right "module" inclusion.

A similar sort of cheat is available if you put the script into
a file, run it as "perl filename"  and only count the number of
chars in the file as significant - a file containing "eval$0"
(6 chars - doesn't need the terminating newline) can be an
extemely complicated program, limited only by the maximum
length permitted for a filename on the supporting OS.


More information about the kw-pm mailing list