Channels ▼
RSS

Web Development

TPJ One Liners


TPJ One-Liners - The Perl Journal


#40

A name game.

s<^([bcdfghjklmnpqrstvwxyz]*)(\w+).*>
<$1$2 $1$2 $1o $1$2 / Bonana-Fanna-Fo-F$2 / 
Fe Fi Mo M$2 / $1$2!>i;

Courtesy of Sean M. Burke
appeared in Issue 15


#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       )#

pars('()', "(123 (456) (789) 0)")

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
appeared in Issue 15


#42

Extract unique elements from a list given a key function

sub unique (&@) {
  my($c,%hash) = shift;
  grep { not $hash{&$c}++ } @_
}

@list = unique { $_       } @list;  
# Remove duplicate strings from @list.

@obj  = unique { $_->name } @obj;   
# Only include one object for 
# for each name.

Courtesy of Don Schwarz
appeared in Issue 15


#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
appeared in Issue 15


#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
appeared in Issue 17


#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
appeared in Issue 17


#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

use vars qw($opt_l $opt_s);            # declaring the two option switches
&getopts('ls');                        # $opt_l and $opt_s are set to 1 or 0
unless($opt_l or $opt_s) {             # unless one switch is true (1)
  die "pmods: A utility to list all installed (nonstandard) modules\n",
      "  Usage: pmods.pl -l  # list each module and all its directories\n",
      "        pmods.pl -s  # list just the module names\n";
}

my $inst  = ExtUtils::Installed->new();
foreach my $mod ( $inst->modules() ) { # foreach of the installed modules
  my $ver = $inst->version($mod);      # version number of the module
     $ver = ($ver) ? $ver : 'NONE';    # for clean operation
  print "MODULE: $mod version $ver\n"; # print module names
  map { print "  $_\n" } $inst->directories($mod) if($opt_l);
}

-Courtesy William H. Asquith et al.
appeared in Issue 17


#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'

appeared in Issue 17


#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.

appeared in Issue 17





Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.
 
Dr. Dobb's TV