August 12, 2001
TPJ One Liners
#40
A name game. Courtesy of Sean M. Burke
#41
Extracting balanced parentheses from a string
use strict
;sub pars
{my( $l,$r
)=map{ "\Q$_"
}split// ,shift;
my(@s,@r ,$i,$o,
$v);for( split/([
$l$r])/, shift){
/$l/and $s[++$o]=
++$i;for $v(1..$o)#
{$r[$v].= $_ if$s[$v]
>0}/$r/and $s[(grep##
$s[$_]== $i,0..$#s)
[0]]=-$i ,--$i<0&& last;}($i=
shift)? wantarray ?@r[grep
-$s[$_ ]==$i,0.. $#s]:$r
[$i]: splice@r, 1;}$,
="\n" ;print pars
(@ ARGV )#
gives you the parenthesized substrings in order of appearance:
(123 (456) (789) 0),(456),(789)
pars('()', "(123 (456) (789) 0)", 2)
in a list context gives you list of substrings, opened on level 2: (456),(789) in scalar context gives you the second substring: (456) Courtesy of Paul Clinger
#42 Extract unique elements from a list given a key function
sub unique (&@) {
my($c,%hash) = shift;
grep { not $hash{&$c}++ } @_
}
Courtesy of Don Schwarz
#43 Seven "Magic Cards." Have a friend think of a number from 1 to 100. Give them cards one at a time and ask if their number is on the card. Mentally sum the first digits of each card with a "yes" answer. Go into trance, say the magic word "Ultrix!" and announce their number. Known to win bar bets.
for $a(0..6){$b=1;for $c(1..100){if($c&2**$a){printf
"%3d ",$c;print"\n"if!($b++%10)}}print"\n\n\n"}
Courtesy of Bill Huston
#44 Asteroid 2000 BF19 was thought to be on a potentially dangerous approach path for us Terrans, with a possible impact in 2022. A Perl program called clomon.pl showed that the asteroid cannot come any closer than 0.038 AU for the next fifty years. Sleep tight! -Based on email from Andrea Milani and Scott Manley
#45 Tracking the progress of a file as it downloads:
perl -e 'BEGIN{$|=1;$f=$ARGV[0];$s=(stat$f)[7];$t=time}
while(sleep 1){printf"\r$f %s bytes at %.2f Kb/s ",
$_=(stat$f)[7],($_-$s)/1024/(time-$t)}'
your_downloading_file -Courtesy Philippe Bruhat
#46 A full list of installed (but nonstandard) modules, and where they are located:
#!/usr/bin/perl -w use strict; # all variables must be declared use Getopt::Std; # import the getopts method use ExtUtils::Installed; # import the package -Courtesy William H. Asquith et al.
#47 Print a message if a daylight savings time change occurs within the next 5 days:
print "\aTIME CHANGE COMING!\n"
if (localtime(time))[8] ne (localtime(time+5*24*60*60))[8];
-Courtesy J.D. Laub
#48 Reverse for syntax to print out Perl's include path:
perl -e 'print "$_\n" for @INC'
#49 You can create a reference to a scalar like so:
$ref = \$var; In recent versions of Perl, you can also say:
$ref = *var{SCALAR};
The same holds for other data types.
|
|
||||||||||||||||||||||||||||
|
|
|
|