SPUG:Minimal Typing for Selections; ideas?

Tim Maher tim at consultix-inc.com
Mon Jun 9 10:44:40 CDT 2003


SPUGsters,

One user of my Shell::POSIX::Select module (see
http://teachmeperl.com/Select.html) requested an enhancement
that I found interesting.

Specifically, instead of making a selection from a menu by its
number,

1)  SPUG   2) SPU   3) SPUD  4) SPUGADELIC

he wanted to be able to type the minimal initial string that
would uniquely identify a choice.

So I whipped up the solution included below, which I rather
like, and which (thus far, at least) seems to work also (I
love it when that happens)! 

I landed on the
	"@choices" =~ /regex/
idea in a moment of inspiration, although I don't think I've ever
seen anybody else do that in Perl code.  Which probably means
there's a better way. 

So, how would you write this program?

#! /usr/bin/perl -w
BEGIN {
	@choices = (
		'ball', 'ball', 'bald', 'balloon', 'ballroom',
	);
}

OUTER: while (1) {
	print "Enter your choice: ";
	$input=<STDIN>;
	defined $input or last;
	chomp $input;

	foreach (@choices) {
		if ( "@choices" =~ /\b($input)\b/ or
		    ( @matches = "@choices" =~ /\b(${input}\w+)\b/g) == 1 ) {
			$choice=$1;
			last OUTER;
		}
		elsif ($1) {
			print"Matched: @matches\n";
			print "Too many matches; type more characters\n";
			last;
		}
		else {
			print "No match\n";
			next OUTER;
		}
	}
}
defined $choice and print "Your choice is $choice\n";
	
-Tim
*------------------------------------------------------------*
| Tim Maher (206) 781-UNIX  (866) DOC-PERL  (866) DOC-UNIX   |
| CEO, JAWCAR ("Just Another White Camel Award Recipient")   |
| tim(AT)Consultix-Inc.Com  TeachMeUnix.Com  TeachMePerl.Com |
*+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-*
|  Watch for my Book: "Minimal Perl for Shell Programmers"   |
*------------------------------------------------------------*



More information about the spug-list mailing list