<?xml version="1.0" encoding="UTF-8"?>



<rss version="2.0" xmlns:blogChannel="http://backend.userland.com/blogChannelModule">

    <channel>
        <title>snippet</title>
        <link>http://prlmnks.org/list/</link>
        <description>RSS feeds from perlmonks.org</description>
        <language>en</language>
        <ttl>5</ttl>

        

<item>
    <title>Gtk2-annotate-draggable texts on image (zentara)</title>
    <link>http://prlmnks.org/html/580829.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/580829.html</guid>

    <description>
        Someone on a newsgroup asked how to do this, and I thought it would be easy( like with Tk  :-) ) However, I found that dragging text in Gtk2 needs 1 undocumented trick..... the text needs to be in a group of it&#39;s own. So I post this to save others the brainf**k. &lt;p&gt;This may be useful for placing text on maps, or identifying people in photos, etc. I know Gimp does that, but this is easierfor quick jobs. It saves a screenshot when desired.&lt;pre class=&quot;block_code&quot;&gt;#!/usr/bin/perluse warnings;use strict;use Gtk2 &#39;-init&#39;;use Gnome2::Canvas;use Glib qw/TRUE FALSE/;my $file = shift or die &quot;Need an image file $!\n&quot;;#draggable text to addmy @text =([&#39;foobar&#39;,20,20,&#39;Arial Bold 60&#39;,&#39;yellow&#39;],           [&#39;foobaz&#39;,20,100,&#39;monospace Bold 14&#39;,&#39;green&#39;],           [&#39;goobar&#39;,20,150,&#39;Sans Bold 24&#39;,&#39;pink&#39;],            );my ( $dragging, $last_x, $last_y ); # item_move globalsmy $window = Gtk2::Window-&gt;new();$window-&gt;set_title(&#39;Text Dragging&#39;);# you may want to make this smaller for small photos$window-&gt;set_size_request(350,250);$window-&gt;signal_connect(&#39;destroy&#39;=&gt;\&amp;delete_event );my $vbox= Gtk2::VBox-&gt;new(FALSE, 1 );$window-&gt;add($vbox);my $scroller = Gtk2::ScrolledWindow-&gt;new();my $canvas = Gnome2::Canvas-&gt;new_aa();$scroller-&gt;add($canvas);my $hbox= Gtk2::HBox-&gt;new(TRUE, 1 );$vbox-&gt;pack_start($hbox,TRUE,TRUE,0);$hbox-&gt;set_border_width(2);$hbox-&gt;add($scroller);$vbox-&gt;pack_start(Gtk2::HSeparator-&gt;new, FALSE, FALSE, 0);my $hbox1= Gtk2::HBox-&gt;new(FALSE, 1 );$vbox-&gt;pack_end($hbox1,FALSE,FALSE,0);$hbox1-&gt;set_border_width(2);my $button1 = Gtk2::Button-&gt;new(&#39;Screenshot Window&#39;);$hbox1-&gt;pack_start( $button1, FALSE, FALSE, 0 );$button1-&gt;signal_connect( clicked =&gt; \&amp;screenshot );my $label_w_markup = Gtk2::Label-&gt;new();$label_w_markup-&gt;set_markup(   &quot;&lt;span  foreground= &#39;black&#39;    size =&#39;15000&#39;&gt;&lt;i&gt;Resize to desired size\n before screenshot&lt;/i&gt;&lt;/span&gt;&quot;);$hbox1-&gt;pack_end( $label_w_markup, FALSE, FALSE, 0 );my $root   = $canvas-&gt;root;my $im = Gtk2::Gdk::Pixbuf-&gt;new_from_file( $file );my $image = Gnome2::Canvas::Item-&gt;new ($root,       &#39;Gnome2::Canvas::Pixbuf&#39;,         pixbuf =&gt; $im,       x      =&gt; 0,                  y      =&gt; 0,       width  =&gt; $im-&gt;get_width,       height =&gt; $im-&gt;get_height,       anchor =&gt; &#39;nw&#39;,       );$canvas-&gt;set_scroll_region(0,0,$im-&gt;get_width,$im-&gt;get_height);$image-&gt;lower_to_bottom();foreach my $t( @text ){ my ($text,$x,$y,$font,$color) = @$t;my $font_desc = Gtk2::Pango::FontDescription-&gt;from_string($font);my $layout = $canvas-&gt;create_pango_layout($text);$layout-&gt;set_font_description($font_desc);my $tgroup = Gnome2::Canvas::Item-&gt;new ($root, &#39;Gnome2::Canvas::Group&#39;,       x =&gt; $x,       y =&gt; $y);    Gnome2::Canvas::Item-&gt;new($tgroup, &#39;Gnome2::Canvas::Text&#39;,                     text=&gt; $text ,                     font_desc=&gt;$font_desc,                     anchor =&gt;&#39;nw&#39;,     fill_color=&gt; $color,                     x=&gt;0, y=&gt;0);$tgroup-&gt;raise_to_top();$tgroup-&gt;signal_connect( &quot;event&quot;, \&amp;item_move );}$window-&gt;show_all();Gtk2-&gt;main();################################################sub delete_event {    Gtk2-&gt;main_quit;    return FALSE;}  #############################################sub item_move {    my ( $item, $event ) = @_;#       print &quot;$item $event-&gt;type\n&quot;;    if ( $event-&gt;type eq &quot;button-press&quot; ) {        $item-&gt;raise_to_top();        $canvas-&gt;window-&gt;set_cursor( Gtk2::Gdk::Cursor-&gt;new(&#39;fleur&#39;) );        $last_x   = $event-&gt;x;        $last_y   = $event-&gt;y;        $dragging = 1;    }    elsif ( $event-&gt;type eq &quot;motion-notify&quot; ) {        if ($dragging) {            my $new_x = $event-&gt;x;            my $new_y = $event-&gt;y;            $item-&gt;move( $new_x - $last_x, $new_y - $last_y );            $last_x = $new_x;            $last_y = $new_y;        }    }    elsif ( $event-&gt;type eq &quot;button-release&quot; ) {         $dragging = 0;         $canvas-&gt;window-&gt;set_cursor (undef);    }return 0;}##############################################################sub get_filename{my $dstr = sprintf q{%02d%s%d}, (split /\s+/,localtime)[2,1,4];return $dstr.time.&#39;.jpg&#39;;} #####################################sub screenshot{#we are going to save the visible canvas windowmy ($width, $height) = $canvas-&gt;window-&gt;get_size;# create blank pixbuf to hold the imagemy $gdkpixbuf = Gtk2::Gdk::Pixbuf-&gt;new (&#39;rgb&#39;,                    0,                    8,                    $width,                    $height);$gdkpixbuf-&gt;get_from_drawable ($canvas-&gt;window,              undef, 0, 0, 0, 0, $width, $height);#only jpeg and png is supported !!!! it&#39;s &#39;jpeg&#39;, not &#39;jpg&#39;$gdkpixbuf-&gt;save ( get_filename() , &#39;jpeg&#39;, quality =&gt; 100);return FALSE;}#####################################################__END__&lt;/pre&gt;
    </description>
</item>

        

<item>
    <title>rightway from US.pm (Intrepid)</title>
    <link>http://prlmnks.org/html/580581.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/580581.html</guid>

    <description>
        &lt;p&gt;Let it be more convenient to use the 3rd-party unix-like sh shells with/from Win32-ish Perls.&lt;/p&gt;&lt;p&gt;This code is written as a module so that it is convenient to use from the command line. Seethe SYNOPSIS section in the embedded POD, below.&lt;/p&gt;&lt;pre class=&quot;block_code&quot;&gt;package US;use strict;use warnings;use vars qw($VERSION @ISA @EXPORT);sub rightway;$VERSION =&#39;0.01&#39;;use base &#39;Exporter&#39;;@EXPORT  = (&#39;rightway&#39;);=head1 NAMEUS.pm - correct slash orientation in file path specs from native Win32 to Perl-canonical form.=head1 VERSIONThis documentation describes version B&lt;0.01&gt; of US.=head1 SYNOPSIS  use US;  use Win32;  use File::Glob &#39;bsd_glob&#39;;  {      local $\ = &quot;\n&quot;;      print for glob(         rightway Win32::GetShortPathName(Win32::GetFolderPath(Win32::CSIDL_COMMON_DOCUMENTS))       . &quot;/*&quot;) ;  }=head1 DESCRIPTIONMakes it more convenient to use the 3rd-party unix-like sh shells with/from Win32-ish Perls.&quot;US&quot; as a name was not chosen with a nationalistic or xenophobic intention. The authorexpects to use this code mainly from the commandline (in &quot;1-liners&quot; as we say in Perl),and as such a short, easy to remember name is a matter of convenience. Ok? &quot;U&quot;==&quot;Unix&quot;,&quot;S&quot;==&quot;Slash&quot;. Thus, &quot;US.pm&quot;.=cut=head1 EXPORTED FUNCTIONS=head2 rightway=cutsub rightway ($) {    my $pstr = shift @_;    $pstr=~ s{\\}{/}g;    $pstr;}1; # US like all modules, should return &quot;TRUE&quot;.__END__=head1 AUTHOR, WARRANTY, COPYRIGHT, &amp; LICENCE INFONO COPYRIGHT, NO WARRANTY, USE AT OWN RISK.Created Oct 25 2006 by Soren Andersen. This code is considered by theauthor to be so obvious and trivial that he hereby releases all claimof rights to (and disclaims any responsibility for) the code, andplaces it in the PUBLIC DOMAIN. Last modified: 25 Oct 2006 at 09:31 AM EDT=cut&lt;/pre&gt;
    </description>
</item>

        

<item>
    <title>csv2sql.pl (ciderpunx)</title>
    <link>http://prlmnks.org/html/579430.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/579430.html</guid>

    <description>
        For various reasons I had a bunch of csv files that should really have been in a database. cvs2sql is a little script that helped me put them there (relatively) painlessly. Perhaps it might be useful for others at some point.&lt;br /&gt;&lt;br /&gt;&lt;pre class=&quot;block_code&quot;&gt;#!/usr/bin/perl=head1 NAMEcsv2sql.pl=head2 VERSION0.1=head1 SYNOPSISread a csv file and convert fields from first line into sqlinsert statements=head2 OPTIONS=over=item  &lt;dbname:tablename&gt; name of the database and table into which we want to insert=back=head1 REQUIREMENTSPerl 5.8.4 (not tried on other versions)Text::CSV_XS IO::Handle=head1 COPYRIGHT AND LICENCE               Copyright (C)2006  Charlie Harvey This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA. Also available on line: http://www.gnu.org/copyleft/gpl.html=head1 SEE ALSO=cutuse strict;use warnings;use Text::CSV_XS;use IO::Handle;my $usage=&quot;Usage: $0 &lt;dbname:tablename&gt;&quot;;die $usage unless($#ARGV==0);my ($db,$table)=(split/:/,shift);die $usage unless($db &amp;&amp; $table);my $sql = &quot;INSERT INTO `$db`.`$table` &quot;;my $csv = Text::CSV_XS-&gt;new ({binary=&gt;1});my $in  = IO::Handle-&gt;new;my $out = IO::Handle-&gt;new;$in-&gt;fdopen(fileno(STDIN), &#39;r&#39;) or die &quot;Can&#39;t fdopen STDIN: $!\n&quot;;$out-&gt;fdopen (fileno (STDOUT), &quot;w&quot;) or die &quot;Cannot fdopen STDOUT: $!\n&quot;;$csv-&gt;parse($in-&gt;getline) or die (&quot;Can&#39;t parse first line of STDIN! $!\n&quot;);my $cols = &quot;(&quot;;my $col_count =0;for ($csv-&gt;fields){  $cols .= &quot;`$_`, &quot;;  $col_count++;}$cols =~ s/, $//;$sql  .= &quot;$cols) VALUES &quot;;while (!$in-&gt;eof) {  IO::Handle-&gt;input_record_separator(&quot;\n&quot;);  my $row = $csv-&gt;getline($in);  next unless defined $row ;  if((@$row) != $col_count) {    warn &quot;Odd row: &quot; ;    warn (join &quot;, &quot;,@$row);    warn &quot;\nExpecting $col_count elements, got &quot; . (@$row) . &quot;\n&quot;;    next;  }  my $vals=&#39;&#39;;  for(@$row) {    $_=~s/&quot;/\\&quot;/g;    $vals.=&#39;&quot;&#39; .$_ .&#39;&quot;, &#39;;  }  $vals =~s/, $//;  $sql.= &quot;($vals), \n&quot;;}undef $in;$sql=~s/, $/;/;$out-&gt;print($sql);undef $out;&lt;/pre&gt;
    </description>
</item>

        

<item>
    <title>Testing hash equality and reporting differences (GrandFather)</title>
    <link>http://prlmnks.org/html/579211.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/579211.html</guid>

    <description>
        &lt;p&gt;I needed to be able to check that two hashes have the same contents as part of a test suite. A [Super Search] turned up [id://89879] which has answers for the equality bit, but doesn&#39;t address the reporting bit.&lt;/p&gt;&lt;p&gt;The following code uses [mod://List::Compare::Functional] to assist in comparing two hashes and reporting differences between them. Note that the application specific warning strings may need to be adjusted for your context. :-)&lt;/p&gt;&lt;pre class=&quot;block_code&quot;&gt;use List::Compare::Functional qw(get_unique get_complement);sub hashesEqual {    my ($have, $want) = @_;    my @keysHave = sort keys %$have;    my @keysWant = sort keys %$want;    my @haveOnly = get_unique ([\@keysHave, \@keysWant]);    my @wantOnly = get_complement ([\@keysHave, \@keysWant]);        if (@haveOnly) {        warn &#39;Unexpected parameters &#39; . (join &#39;,&#39;, @haveOnly) . &quot; for email send\n&quot;;        return;    }        if (@wantOnly) {        warn &#39;Expected parameters &#39; . (join &#39;,&#39;, @haveOnly) . &quot; missing for email send\n&quot;;        return;    }        my $ok = 1;    for (@keysHave) {        next if $have-&gt;{$_} eq $want-&gt;{$_};        $ok = undef;        warn &quot;Email send parameter $_ expected &#39;$want-&gt;{$_}&#39;, got &#39;$have-&gt;{$_}&#39;\n&quot;;    }        return $ok;}&lt;/pre&gt;
    </description>
</item>

        

<item>
    <title>How to quickly display an image on a webpage via perl (Melly)</title>
    <link>http://prlmnks.org/html/578167.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/578167.html</guid>

    <description>
        &lt;p&gt;This one seems to come up a lot in Seekers, so I thought I&#39;d drop a simple script in here.&lt;/p&gt;&lt;p&gt;Although this script displays a random image from a specified directory, the principle should be adaptable to any image display code... basically, use a &amp;quot;Location:&amp;quot; redirect...&lt;/p&gt;&lt;pre class=&quot;block_code&quot;&gt;#!/usr/bin/perl -wT use strict;# Call in img tag - e.g.: &lt;img src=&quot;randimage.cgi&quot; border=&quot;2&quot;&gt;my @files = glob(&quot;./jpegs/*.jpg&quot;);print &quot;Location: $files[int(rand @files)]\n\n&quot;;&lt;/pre&gt;
    </description>
</item>

        

<item>
    <title>HTML Tables - populating TD from an array (Melly)</title>
    <link>http://prlmnks.org/html/578129.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/578129.html</guid>

    <description>
        &lt;p&gt;Although it&#39;s fairly easy to write a series of &amp;quot;print &#39;&amp;lt;TD&amp;gt;&#39;, $_-&gt;[0], &#39;&amp;lt;/TD&amp;gt;&#39;&amp;quot; statements to populate table TD elements with the contents of an array, it&#39;s not necessarily obvious how to do it using the more formal CGI syntax.&lt;/p&gt;&lt;p&gt;However, [davidrw] [id://577404|enlightened me] on the use of [doc://map] for such cases.&lt;/p&gt;&lt;pre class=&quot;block_code&quot;&gt;use CGI qw(:standard);@links = (  [&#39;CPAN&#39;, &#39;http://cpan.perl.org&#39;],  [&#39;Active State&#39;, &#39;http://www.activestate.com&#39;],  [&#39;Perl Monks&#39;, &#39;http://www.perlmonks.org&#39;]);print start_html(&#39;Perl Links&#39;);print table({-border=&gt;1},  Tr([    th([&#39;Site&#39;, &#39;URL&#39;]),    map{      td([$$_[0], a({-href=&gt;$$_[1]},$$_[1])])    }@links  ]));print end_html();&lt;/pre&gt;
    </description>
</item>

        

<item>
    <title>METAreqWeb - overview of CPAN dist prerequisites (Intrepid)</title>
    <link>http://prlmnks.org/html/577441.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/577441.html</guid>

    <description>
        &lt;p&gt;&lt;b&gt;Solution to a chatterbox FAQ: what modules required are shipped with Perl? Which are already on the system?&lt;/b&gt;&lt;/p&gt;&lt;p&gt;  This cli script sits at the corner of my desk awaiting the next  time I am looking up Perl modules at search.cpan.org.&lt;p&gt;  Finding the module I am interested in, I examine its directory  (like: http://search.cpan.org/~moconnor/YAML-AppConfig-0.16/ )  ... there are a number of files listed, including Makefile.PL (or  Build.PL), MANIFEST, README, and ...META.yml.&lt;p&gt;  I context-click on the META.yml file and click &quot;Copy Link Location&quot;  to put the URL pointing to the META.yml file on the system clipboard.  Then I run the snippet below to quickly get the overview of this  module&#39;s prerequisites.&lt;pre class=&quot;block_code&quot;&gt;#!/usr/bin/env perl# Last modified: 10 Oct 2006 at 12:02 PM EDT# Author: Soren Andersen &lt;intrepid -AT- perlmonk *dot* org&gt;# $Id$use strict;use warnings;use YAML qw/ Load Dump LoadFile /;use LWP::Simple;use POSIX qw(isatty);sub coremod { &quot;&quot; };sub hr;sub dimmer;sub find_longest_keystring;sub mtest;sub testyml {    my $metayml_uri =      (shift(@_) || &#39;http://search.cpan.org/src/RUBYKAT/html2dbk-0.03/META.yml&#39;);    my $docu;    if( $docu = get $metayml_uri ) {return $docu    }    die &quot;Could not retrieve &#39;$metayml_uri&#39;. Network troubles? Bad URI?&quot;;}## And now a brief interlude of presentational trivia, not very interestingmy $screenW = $ENV{COLUMNS} || 42;my $unxterm = isatty(*STDOUT) &amp;&amp; $^O !~/MSWin32/ ? 1 : 0;if ($unxterm) {    require Term::ANSIColor and import Term::ANSIColor (&#39;colored&#39;);   #print colored(&quot;Using Term::ANSIColor&quot;, &#39;dark white&#39;), &quot;\n&quot;;} ## done with interlude, back to main showmy $metadoc = testyml (shift(@ARGV) || undef);my $modmeta = Load( $metadoc );if( $modmeta-&gt;{requires} ) {    my ($k,$v);    my $fmtlen;    my %reqrs = %{                   my($mkl,@hash)                    = find_longest_keystring($modmeta-&gt;{requires});                   $fmtlen = $mkl || 28;                   my $rh = {@hash};                 };    if (eval &quot;use Module::CoreList; 1&quot; and not $@)    {        no warnings (&#39;redefine&#39;,&#39;once&#39;);        sub coremod        {            my($pm) = @_;            my $presence_in_core = $Module::CoreList::version{$]}{$pm};            return &quot;\n&quot; unless defined $presence_in_core;            my $pmv;            $pmv = $presence_in_core == 0 ? &quot;without a VERSION number&quot;               : &quot;version $presence_in_core&quot;;            my $prn  = Module::CoreList-&gt;first_release($pm);            my $note = &lt;&lt;&quot;        ELEPHANT&quot;;  CORE: $pm was first included in the core Perl distribution at Perl release $prn        The present Perl system shipped with $pm $pmv        ELEPHANT            return $note;        }    }    print hr;    printf &lt;&lt;&quot;        YODOWN&quot; %-${fmtlen}s %s   %s%s        YODOWN =&gt; ($k,($v eq &#39;0&#39;? &#39;any version&#39;:&quot;at version $v&quot;) , mtest($k), coremod($k))           while ($k,$v) = each %reqrs;    print hr;} else # there are no prerequisite modules or pragmata listed    {  print &quot;No requires for $modmeta-&gt;{name}\n&quot;; }sub mtest{    my $installed_version;    my $wherep;    my $modname = shift();    my $modlibp = $modname;    $modlibp =~ s{ :: } {/}xg;    $modlibp .= &#39;.pm&#39;;    my $can_req = eval &quot;use $modname; 1;&quot;;  if   ($can_req and not $@)    {        no strict &#39;refs&#39;;        $wherep = $INC{ $modlibp };        $installed_version = (${$modname.&#39;::VERSION&#39;}) || 0;    }  else    {        return colored(sprintf(            &quot;%-32s is not installed&quot;=&gt; $modname) , &#39;cyan&#39;)           if ($unxterm);        return sprintf(            &quot;%-32s is not installed&quot;=&gt; $modname)    }        if ($unxterm) {    colored(        sprintf(&#39;%-32s v%4s found as %s&#39;         =&gt; ($modname , $installed_version , $wherep))      , &#39;magenta&#39; );    } else {        sprintf(&#39;%-32s v%-4s found as %s&#39;         =&gt; ($modname , $installed_version , $wherep))    }}sub find_longest_keystring{    my %rethash = %{ shift() };    return () unless 1 * @{[ %rethash ]};    delete $rethash{&#39;perl&#39;};    my $l_maxed_at = 0;    for (keys(%rethash)) {$l_maxed_at = length() &gt; $l_maxed_at ? length() : $l_maxed_at    }    return ( $l_maxed_at, %rethash );}sub hr{    my $decor = $unxterm      ? dimmer(&quot;-&quot; x $screenW)      :       (&quot;-&quot; x $screenW);    $decor . &quot;\n&quot;;}sub dimmer{    colored( shift() , &#39;dark white&#39; );}__END__=head1 NAMEMETAreqWeb=head1 SYNOPSIS  ./METAreqWeb [ &lt;http://search.cpan.org/src/MOCONNOR/YAML-AppConfig-0.16/META.yml&gt; ]=cut&lt;/pre&gt;
    </description>
</item>

        

<item>
    <title>Tk Realtime data aquisition (zentara)</title>
    <link>http://prlmnks.org/html/577181.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/577181.html</guid>

    <description>
        [id://576881] prompted me to try it. This is a realtime Tk data graph, getting the data through a socket connection. I made it as simple as I could for demo purposes. It will monitor for 86400 seconds ( broke the minutes into 10&#39;ths). I also just let the sending script send a count (0..86400), mostly so I could speed it up for testing. In reality, you would want the sender to send the time of it&#39;s read, instead of the count.&lt;p&gt;I noticed that as the data array(for the curve) got bigger, the cpu rate would rise to handle reconfiguring the curve with the huge array. So I broke the day into 500 second segments, which limits the point data array to 1000 elements. On my machine the cpu usage varied between 5 and 10%.&lt;p&gt;There are 2 scripts, the socket-sender-test and the main Tk program.The socket-sender-test&lt;pre class=&quot;block_code&quot;&gt;#!/usr/bin/perluse IO::Socket;my $machine_addr = &#39;localhost&#39;;$sock = new IO::Socket::INET(PeerAddr=&gt;$machine_addr,      PeerPort=&gt;7070,      Proto=&gt;&#39;tcp&#39;,      );die &quot;Could not connect: $!&quot; unless $sock;foreach my $count(1..86400){  my $temp = 800 + int(rand 100);  my $send = &quot;$count $temp&quot;;  print $sock &quot;$send\n&quot;;  print &quot;$send\n&quot;;  select(undef,undef,undef,.1) ;}close ($sock);__END__&lt;/pre&gt;And the Tk monitor&lt;pre class=&quot;block_code&quot;&gt;#!/usr/bin/perluse warnings;use strict;use IO::Socket;use Tk;$|++;my $listen = IO::Socket::INET-&gt;new(    Proto       =&gt; &#39;tcp&#39;,    LocalPort   =&gt; 7070,    Listen      =&gt; 1,    Reuse       =&gt; 1,) or die &quot;Can&#39;t create listen socket : $!\n&quot;;my $margin = 50;my $offset = 20;   #axis offsetmy $x_max = 86400;my $y_max = 1000;my $connected = &#39;Not Connected&#39;;my %data;            #why continuosly update the entire                     #data set? cpu rate will climb, so my $current_seg = 0; #break graph into 500 second segments                     #to avoid cpu rate climbing, will create     # 86400/500 =~ 175 lines (data) segemntsmy $mw = tkinit;$mw-&gt;fileevent($listen, &#39;readable&#39;, sub { new_connection($listen) });my $scanvas = $mw-&gt;Scrolled(&#39;Canvas&#39;,                 -width =&gt; 620,  -height =&gt; 420,                 -scrollregion =&gt; [-$margin,-$margin,                   $x_max + $margin,                   $y_max + $margin + $offset ], -bg =&gt; &#39;black&#39;)-&gt;pack();&amp;build_axis();my $canvas = $scanvas-&gt;Subwidget(&#39;scrolled&#39;);$canvas-&gt;Tk::bind(&quot;&lt;Button-1&gt;&quot;, [ \&amp;print_xy, Ev(&#39;x&#39;), Ev(&#39;y&#39;) ]);sub print_xy {  my ($canv, $x, $y) = @_;  print &quot;(x,y) = &quot;, $canv-&gt;canvasx($x), &quot;, &quot;, $canv-&gt;canvasy($y), &quot;\n&quot;;}#for simplicity create the lines firstforeach my $line(0..172){  push @{$data{$line}{&#39;data&#39;}},0,0,0,0; #initilize, will remove later  $data{$line}{&#39;line_obj&#39;} = $canvas-&gt;createLine(                            @{$data{$current_seg}{&#39;data&#39;}},                          -width =&gt; 1,                          -smooth =&gt; 1,  -fill =&gt; &#39;lightgreen&#39;);}my $subframe = $mw-&gt;Frame(-background =&gt;&#39;gray50&#39;)-&gt;pack(-fill =&gt; &#39;x&#39;);$subframe-&gt;Button(-text =&gt;&#39;Exit&#39;,            -background =&gt; &#39;hotpink&#39;,            -activebackground =&gt; &#39;red&#39;,    -command =&gt; sub{ exit }            )-&gt;pack(-side=&gt;&#39;left&#39;,-padx=&gt;40);$subframe-&gt;Label(-textvariable =&gt; \$connected,            -background =&gt; &#39;black&#39;,    -foreground =&gt; &#39;green&#39;,            )-&gt;pack(-side=&gt;&#39;left&#39;);MainLoop;#######################################################################sub new_connection {    my ($listen) = @_;    my $client = $listen-&gt;accept() or warn &quot;Can&#39;t accept connection&quot;;    $client-&gt;autoflush(1);    $mw-&gt;fileevent($client, &#39;readable&#39;, sub { handle_connection($client) });    $connected = &#39;Connected&#39;;}sub handle_connection {    my ($client) = @_;    my $message = &lt;$client&gt;;#    print &quot;$message\n&quot;;#    if( $message = eof){print &quot;crashed\n&quot;}    if ( defined $message ) {     $message =~ s/[\r\n]+$//;     my ($x, $y) = split( &quot; &quot;, $message);            if( $#{$data{$current_seg}{&#39;data&#39;}} &gt;  1000 ){  #2 entries per point       #initialize next segmnet, pop off last 2 of previous segment       my($xo,$yo) =  @{$data{ $current_seg}{&#39;data&#39;}}[-2, -1 ];       $current_seg++;       print &quot;current seg $current_seg\n&quot;;           #inititialize by overwriting the initial 0,0,0,0       ${$data{$current_seg}{&#39;data&#39;}}[0] = $xo;       ${$data{$current_seg}{&#39;data&#39;}}[1] = $yo;       ${$data{$current_seg}{&#39;data&#39;}}[2] = $xo;       ${$data{$current_seg}{&#39;data&#39;}}[3] = $yo;      }        push @{$data{$current_seg}{&#39;data&#39;}}, $x, $y;        $scanvas-&gt;coords( $data{$current_seg}{&#39;line_obj&#39;}, @{$data{$current_seg}{&#39;data&#39;}} );     #$scanvas-&gt;xviewScroll(1,&#39;units&#39;);      $scanvas-&gt;xview(&#39;moveto&#39;, $x/86400 );#     $text-&gt;insert(&#39;end&#39;, &quot;Got message [$message]\t&quot;);#     $text-&gt;see(&#39;end&#39;);    }    else {       #$text-&gt;insert(&#39;end&#39;, &quot;Connection Closed\n&quot;);       #$text-&gt;see(&#39;end&#39;);      $client-&gt;close();      $connected = &#39;NOT Connected&#39;;      print &quot;not connected\n&quot;;     }}##############################################################sub build_axis{# axismy $xaxis = $scanvas-&gt;createLine( 0, $y_max + $offset, $x_max, $y_max + $offset,                          -width =&gt; 1,  -fill =&gt; &#39;lightblue&#39;);my $yaxis = $scanvas-&gt;createLine( 0, $y_max + $offset ,0,0,                          -width =&gt; 1,  -fill =&gt; &#39;lightgreen&#39;);# x axis ticksmy $tflag;my $labflag;my $min = 0;my $minflag = 0;my $hour = 0;my $hourflag = 0;my $tlength;my $color;for(1..$x_max){    $tflag = 0;    $tlength = 5;    $color = &#39;white&#39;;    $hourflag = 0;    $minflag = 0;    $labflag = 0;    if( ($_ % 10) == 0 ){ $tflag = 1 }  #minutes are broken into 10 sec intervals    if( ($_ % 60) == 0 ){ $tlength = 15 ;                           $color = &#39;yellow&#39;;   $min++;   $minflag = 1;  $labflag = 1;  }      if( ($_ % 3600) == 0 ){ $tlength = 25;                             $color = &#39;hotpink&#39;;                             $hour++;     $hourflag = 1;    $labflag = 1;    $min = 0;    $minflag = 0;   }    if( $tflag ){      $scanvas-&gt;createLine( $_, $y_max + $offset, $_, $y_max + $offset + $tlength,                          -width =&gt; 1,  -fill =&gt; $color);                   if($labflag){            my $label;    if($minflag){ $label = $min; }            if($hourflag){ $label = $hour; }          $scanvas-&gt;createText( $_,  $y_max + $offset + 1.2*$tlength,                           -text =&gt; $label,                   -fill =&gt; $color,   -anchor =&gt; &#39;n&#39;,   );           }     }}# y axis ticksmy $uflag;my $midflag;my @array = reverse(0..$y_max );for(@array){    my $num = $y_max - $_;  #reverse normal axis    $tflag = 0;    $tlength = 5;    $color = &#39;white&#39;;    $uflag = 0;    $midflag = 0;    $labflag = 0;    if( ($num % 10) == 0 ){ $tflag = 1 }    if( ($num % 50) == 0 ){ $tlength = 10 ;                           $color = &#39;yellow&#39;;   $midflag = 1;  $labflag = 1;  }      if( ($num % 100) == 0 ){ $tlength = 20;                             $color = &#39;hotpink&#39;;                             $uflag = 1;    $labflag = 1;    $midflag = 0;   }    if( $tflag ){      $scanvas-&gt;createLine( 0 - $tlength, $num + $offset, 0, $num + $offset,                          -width =&gt; 1,  -fill =&gt; $color);                   if($labflag){            my $label;    if($midflag){ $label =  $num; }            if($uflag){ $label =  $num; }          $scanvas-&gt;createText( -20 ,  $y_max + $offset - $num ,                           -text =&gt; $label,                   -fill =&gt; $color,   -anchor =&gt; &#39;e&#39;,   );           }     }}$scanvas-&gt;xview(&#39;moveto&#39;,0);$scanvas-&gt;yview(&#39;moveto&#39;,1);}&lt;/pre&gt;
    </description>
</item>

        

<item>
    <title>Timer for data recive????? (samirpatry)</title>
    <link>http://prlmnks.org/html/576499.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/576499.html</guid>

    <description>
        &lt;br&gt; i have a client/server program.Now i want to set timer for the same.That means if client send a request to the server and with 10 sec if the particular response is not arrive to the client then it will show the timeout.After that it will resend the request to the server and increase the value of timer.&lt;/br&gt;&lt;br&gt;The platform is windows&lt;/br&gt;&lt;pre class=&quot;block_code&quot;&gt;&lt;/pre&gt;
    </description>
</item>

        

<item>
    <title>Customize your Test::More (Ovid)</title>
    <link>http://prlmnks.org/html/574954.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/574954.html</guid>

    <description>
        &lt;p&gt;The problem:  your code sometimes does things that you do not want it to do while tests are running.  Mocking up objects or methods is all fine and dandy, but if in the middle of a chunk of procedural code, you find yourself sending email by printing to a filehandle, that can be difficult to trap.&lt;/p&gt;&lt;p&gt;One solution is to wrap this code in a conditional, checking to see if &lt;tt&gt;$ENV{HARNESS_ACTIVE}&lt;/tt&gt; or something is true.  However, if you run your test script directly through perl and not through &lt;tt&gt;prove&lt;/tt&gt;, that environment variable won&#39;t be set.  One way of handling this is to use a custom &lt;tt&gt;Test::More&lt;/tt&gt; module.  The following snippet shows how to write one.  It&#39;s a drop-in replacement for &lt;tt&gt;Test::More&lt;/tt&gt;.  You can include any behaviors you want, thereby making it easier for code to know if it&#39;s being run in a test environment.&lt;/p&gt;&lt;pre class=&quot;block_code&quot;&gt;  package My::Test::More;  use Test::Builder::Module;  @ISA = qw(Test::Builder::Module);    use Test::More;  @EXPORT = @Test::More::EXPORT;    # add whatever you need here  $ENV{WE_BE_TESTING} = 1;  1;&lt;/pre&gt;
    </description>
</item>

        

<item>
    <title>Tk photo pixel colors (zentara)</title>
    <link>http://prlmnks.org/html/574745.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/574745.html</guid>

    <description>
        I saw this type of app in the Gtk2 examples, and thought it would be nice to have a Tk version. It loads a bmp, gif, jpg, or png and gives the pixel position, decimal rgb color, hex rgb color, and a color swatch.&lt;pre class=&quot;block_code&quot;&gt;#!/usr/bin/perluse warnings;use strict;use Tk;use Tk::JPEG;use Tk::PNG;my $file = shift || die &quot;need a bmp, gif,jpg or png as arg 1\n&quot;;my $mw  = Tk::MainWindow-&gt;new;my $topframe = $mw-&gt;Frame(-bg =&gt; &#39;black&#39;)-&gt;pack(-fill=&gt;&#39;x&#39;);my $tf1 = $topframe-&gt;Frame(-bg =&gt; &#39;black&#39;)-&gt;pack(-side=&gt;&#39;left&#39;,-fill=&gt;&#39;x&#39;);my $xy = $tf1-&gt;Label(-text =&gt; &#39;  X - Y  &#39;,                       -fg =&gt; &#39;hotpink&#39;,       -bg =&gt; &#39;black&#39;,                  )-&gt;pack(-side =&gt; &#39;top&#39;,-padx=&gt;2);my $rgb = $tf1-&gt;Label(-text =&gt; &#39;R - G - B&#39;,                       -fg =&gt; &#39;hotpink&#39;,       -bg =&gt; &#39;black&#39;,                  )-&gt;pack(-side =&gt; &#39;top&#39;, -padx=&gt;2);my $hex = $tf1-&gt;Label(-text =&gt; &#39;   HEX   &#39;,                       -fg =&gt; &#39;hotpink&#39;,       -bg =&gt; &#39;black&#39;,                  )-&gt;pack(-side =&gt; &#39;top&#39;,-padx=&gt;2);my $tf2 = $topframe-&gt;Frame(-bg =&gt; &#39;black&#39;)-&gt;pack(-side=&gt;&#39;left&#39;,-fill=&gt;&#39;x&#39;);my $xycurrent;my $xyr = $tf2-&gt;Label(-textvariable =&gt; \$xycurrent,                       -fg =&gt; &#39;lightgreen&#39;,       -bg =&gt; &#39;black&#39;,                  )-&gt;pack(-side =&gt; &#39;top&#39;,-padx=&gt;2);my $rgbcurrent;my $rgbr = $tf2-&gt;Label(-textvariable =&gt; \$rgbcurrent,                       -fg =&gt; &#39;lightgreen&#39;,       -bg =&gt; &#39;black&#39;,                  )-&gt;pack(-side =&gt; &#39;top&#39;, -padx=&gt;2);my $hexcurrent;my $hexr = $tf2-&gt;Label(-textvariable =&gt; \$hexcurrent,                       -fg =&gt; &#39;lightgreen&#39;,       -bg =&gt; &#39;black&#39;,                  )-&gt;pack(-side =&gt; &#39;top&#39;,-padx=&gt;2);my $swatch = $topframe-&gt;Label(                     -text =&gt; &#39;       &#39;,                     -bg=&gt;&#39;black&#39;,                    )-&gt;pack(-side=&gt;&#39;left&#39;,-fill=&gt;&#39;y&#39;,-pady =&gt; 5); my $tf3 = $mw-&gt;Frame(-bg =&gt; &#39;hotpink&#39;)-&gt;pack(-fill=&gt;&#39;x&#39;);my $divider = $tf3-&gt;Label(                     -text =&gt; &#39;       &#39;,                     -bg=&gt;&#39;hotpink&#39;,                    )-&gt;pack(-side=&gt;&#39;left&#39;,-fill=&gt;&#39;y&#39;,-pady =&gt; 1); my $can = $mw-&gt;Scrolled(&#39;Canvas&#39;,                 -height =&gt; 400, -width  =&gt; 400, -scrollbars =&gt; &#39;osoe&#39;,                 -highlightthickness=&gt;0, -borderwidth =&gt;0,                 )-&gt;pack( -fill =&gt;&#39;both&#39;,-expand=&gt;1);my $realcan = $can-&gt;Subwidget(&#39;scrolled&#39;);my $img = $mw-&gt;Photo( -file =&gt; &quot;$file&quot;,       -palette =&gt; &#39;256/256/256&#39; );$can-&gt;createImage(0,0,  #hardcoded offset                  -image =&gt; $img,   -anchor =&gt; &#39;nw&#39;,  -tags =&gt; [&#39;img&#39;],   );my @bbox = $can-&gt;bbox( &#39;img&#39;  );$can-&gt;configure(-scrollregion =&gt; [@bbox] );$realcan-&gt;Tk::bind(&quot;&lt;Motion&gt;&quot;, [ \&amp;print_xy, Ev(&#39;x&#39;), Ev(&#39;y&#39;) ]);$realcan-&gt;Tk::bind(&quot;&lt;Leave&gt;&quot;, sub{            $xycurrent  = &#39;&#39;;            $rgbcurrent = &#39;&#39;;    $hexcurrent = &#39;&#39;;   });MainLoop();############################################################ a cheap hack to prevent the Tk Photo object from issuing# an out of bounds error if the window is expanded bigger # than the photosub Tk::Error { }#####################################################sub print_xy {  my ($canv, $x, $y) = @_;  $xycurrent = $canv-&gt;canvasx($x).&#39; - &#39;.$canv-&gt;canvasy($y);        my($r,$g,$b) = $img-&gt;get($canv-&gt;canvasx($x), $canv-&gt;canvasy($y) );   $rgbcurrent = sprintf(&#39;%.3d&#39;, $r).&#39;-&#39;.sprintf(&#39;%.3d&#39;, $g).&#39;-&#39;.sprintf(&#39;%.3d&#39;, $b);   #convert to hex from decimal   $r = sprintf(&#39;%.2x&#39;, $r);   $g = sprintf(&#39;%.2x&#39;, $g);   $b = sprintf(&#39;%.2x&#39;, $b);   $hexcurrent = $r.&#39;-&#39;.$g.&#39;-&#39;.$b; $swatch-&gt;configure(-bg=&gt;&quot;#$r$g$b&quot;);}&lt;/pre&gt;
    </description>
</item>

        

<item>
    <title>WMI: Classes (jschollen)</title>
    <link>http://prlmnks.org/html/574706.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/574706.html</guid>

    <description>
        The last part of the triology ;-)After retrieving all namespaces and all the properties of the classes, this piece of code retrieves al the classes within a given namespace.&lt;br&gt;&lt;br&gt;It works for me (&#39;till now) and I&#39;m using it on Windows XP SP2.&lt;br&gt;&lt;br&gt;(thanks again to the Microsoft Scripting Guys for the vb code)&lt;pre class=&quot;block_code&quot;&gt;use Win32::OLE(&#39;in&#39;);use strict;my $stepOk = 1;my $errorMsg = &quot;&quot;;my $wmiService = &quot;&quot;;my $computer   = &quot;.&quot;; # Computer to connect to: . = local hostmy $namespace  = &quot;\\root\\cimV2&quot;; # Namespace to connect tomy @classes    = ();$wmiService = Win32::OLE-&gt;GetObject(&quot;winmgmts:\\\\&quot;.$computer.$namespace);my $subDevices = $wmiService-&gt;SubclassesOf();foreach my $subDevProp ( in( $subDevices ) ){  print &quot;Class $count: &quot;.$subDevProp-&gt;{Path_}-&gt;{Path}.&quot;\n&quot;;  if($subDevProp-&gt;{Path_}-&gt;{Path} =~ /.*:(.*)/)  {    my $class = $1;    print &quot;Detected class: $class\n&quot;;    push(@classes,$class);  }}# Scripted by jschollen# Thanks to the Microsoft Scripting Guys&lt;/pre&gt;
    </description>
</item>

        

<item>
    <title>WMI: Namespaces (jschollen)</title>
    <link>http://prlmnks.org/html/574704.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/574704.html</guid>

    <description>
        This peace of code helps you retrieves all the namespaces that are on your pc.&lt;br&gt;All the namespaces are printed to the screen and are stored in the array @nameSpaces.&lt;br&gt;(Note that the stored namespaces are using a single backslash, which should be replaced by a double backslash in order to connect to it.)&lt;br&gt;&lt;br&gt;The code works for me and I tested it on Windows XP SP2.&lt;br&gt;&lt;br&gt;(Thanks to the Microsoft Scripting Guys for providing the vb code).&lt;pre class=&quot;block_code&quot;&gt;#!/usr/local/perluse Win32::OLE(&#39;in&#39;);use strict;# Variablesmy $stepOk     = 1;my $errorMsg   = &quot;&quot;;my $wmiService = &quot;&quot;;my $computer   = &quot;.&quot;; # Computer to connect to: . = local hostmy @nameSpaces = ();enumNameSpaces(&quot;root&quot;);sub enumNameSpaces{  my $nameSpaceStr = shift;    print $nameSpaceStr.&quot;\n&quot;;  push(@nameSpaces,$nameSpaceStr);    $wmiService = Win32::OLE-&gt;GetObject(&quot;winmgmts:\\\\&quot;.$computer.&quot;\\&quot;.$nameSpaceStr);  ($stepOk = 0) unless $wmiService;  if(! $stepOk)  {    $errorMsg = &quot;Unable to open wmi services&quot;;    print $errorMsg.&quot;\n&quot;;  }    my $subDevices = $wmiService-&gt;InstancesOf(&quot;__NAMESPACE&quot;);    foreach my $subDevProp ( in( $subDevices ) )  {    enumNameSpaces($nameSpaceStr.&quot;\\&quot;.$subDevProp-&gt;{Name});  }}# Scripted by jschollen# Thanks to the Microsoft Scripting Guys&lt;/pre&gt;
    </description>
</item>

        

<item>
    <title>WMI: display Class properties (jschollen)</title>
    <link>http://prlmnks.org/html/574374.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/574374.html</guid>

    <description>
        This piece of code displays all the properties (with their values) that are available for a WMI class method.With it, you have to change just 1 parameter in stead off all the properties.&lt;br&gt;&lt;br&gt;By changing the variables, you can change either the computer, namespace or class method.&lt;br&gt;&lt;br&gt;I&#39;ve tested in on an Windows XP SP2 machine, and had no problems so far.&lt;br&gt;&lt;br&gt;(Thanks to the Microsoft Scripting guys for the vb code)&lt;pre class=&quot;block_code&quot;&gt;#!/usr/local/perluse Win32::OLE(&#39;in&#39;);use strict;my $stepOk = 1;my $errorMsg = &quot;&quot;;# Variablesmy $wmiService = &quot;&quot;;my $computer   = &quot;.&quot;; # Computer to connect to: . = local hostmy $namespace  = &quot;\\root\\cimV2&quot;; # Namespace to connect tomy $class      = &quot;CIM_Controller&quot;; # Class Method from which you want to retrieve the properties$wmiService = Win32::OLE-&gt;GetObject(&quot;winmgmts:\\\\&quot;.$computer.$namespace);($stepOk = 0) unless $wmiService;if(! $stepOk){  $errorMsg = &quot;Unable to open wmi services&quot;;  print $errorMsg.&quot;\n&quot;;}else{  my $subDevices = $wmiService-&gt;ExecQuery(&quot;Select * from &quot;.$class);  print &quot;***********************************************\n&quot;;  foreach my $subDevProp ( in( $subDevices ) )  {    foreach my $prop (in($subDevProp-&gt;{Properties_}))    {      print &quot;***** &quot;.$prop-&gt;{Name}.&quot;: &quot;.$prop-&gt;{Value}.&quot;\n&quot;;    }    print &quot;*********************************************\n&quot;;  }}# Scripted by jschollen# Thanks to the Microsoft Scripting Guys&lt;/pre&gt;
    </description>
</item>

        

<item>
    <title>Saving spreadsheets to HTML that have quotes in them. (blue_cowdawg)</title>
    <link>http://prlmnks.org/html/574274.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/574274.html</guid>

    <description>
        &lt;p&gt;In one of my hobby related tasks I get to create schedules for workers working rings at a dog trial.  One of the annoyances I run into is when I have cells that have something like&lt;pre class=&quot;block_code&quot;&gt;20&quot; - 24&quot; walk through&lt;/pre&gt;the quotes and the dashes end being morphed into wide characters when I save the spreadsheet as HTML. When those wide characters get sent to a browser they end up looking like garbage instead of the dashes and quotes that I started with. &lt;/p&gt;&lt;p&gt;Using the &lt;tt class=&quot;inline_code&quot;&gt;od -c&lt;/tt&gt; command I found that therewas an offending set of octals that showed up repeatedly everywhere that this offense occured. What follows is a one liner that removes them quite nicely. &lt;pre class=&quot;block_code&quot;&gt; perl -spi -e &#39;s/\342\200\235/&quot;/g&#39; dvgsdc.jsp&lt;/pre&gt;
    </description>
</item>

        

<item>
    <title>Get US stock tables from WSJ (Scott7477)</title>
    <link>http://prlmnks.org/html/573628.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/573628.html</guid>

    <description>
        After years of posting daily stock prices on its website in practically useless pdf files; the Wall Street Journal has set up a page where one can download daily stock price data as CSV files. This script simply goes to the relevant page at WSJ.com, downloads the files, and names each file with the market acronym and the day&#39;s date concatenated.&lt;pre class=&quot;block_code&quot;&gt;use strict;use LWP::Simple;while (my $downloadurl = &lt;DATA&gt;){my $x=&quot;http://online.wsj.com/internal/mdc/&quot;;my $finurl=$x.$downloadurl;my @urlsplit=split /\./, $downloadurl; my $now_string = substr(localtime,0,11);my $savefilename = $urlsplit[0].$now_string;print $savefilename;print &quot;\n&quot;;my $status = getstore($finurl,$savefilename);print $status.&quot;\n&quot; if is_success($status);}__END__;NYSE.csv?mod=stocksdailyNasdaq.csv?mod=stocksdailySCAP.csv?mod=stocksdailyAMEX.csv?mod=stocksdaily&lt;/pre&gt;
    </description>
</item>

        

<item>
    <title>List all perldoc FAQs (Dietz)</title>
    <link>http://prlmnks.org/html/573577.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/573577.html</guid>

    <description>
        &lt;p&gt;This will list all FAQs from &lt;tt class=&quot;inline_code&quot;&gt;perlfaq[1-9]&lt;/tt&gt; without their answers.&lt;br&gt;Just a modification of already imported subroutines from &lt;tt class=&quot;inline_code&quot;&gt;Pod::Perldoc&lt;/tt&gt;.&lt;/p&gt;&lt;p&gt;Sample output:&lt;/p&gt;&lt;pre class=&quot;block_code&quot;&gt;$ perldocfaqsWhat is Perl?Who supports Perl?  Who develops it?  Why is it free?..snip...What machines support perl?  Where do I get it?...snip...How do I fetch/put an FTP file?How can I do RPC in Perl?&lt;/pre&gt;Lists all FAQs line by line&lt;br&gt;&lt;br&gt;&lt;pre class=&quot;block_code&quot;&gt;$ perldocfaqs -n[perlfaq1 - 01]  What is Perl?[perlfaq1 - 02]  Who supports Perl?  Who develops it?  Why is it free?...snip...[perlfaq2 - 01]  What machines support perl?  Where do I get it?...snip...[perlfaq9 - 25]  How do I fetch/put an FTP file?[perlfaq9 - 26]  How can I do RPC in Perl?&lt;/pre&gt;Called with &#39;-n&#39; lists all FAQs with leading file info and faq number&lt;br&gt;&lt;pre class=&quot;block_code&quot;&gt;#!/usr/bin/perluse strict;use warnings;use File::Basename &#39;fileparse&#39;;use Pod::Perldoc;my $show_faqnums = (shift||0) eq &#39;-n&#39; ? 1 : 0;@ARGV = qw(-oText -q.);no warnings &#39;redefine&#39;;sub Pod::Perldoc::search_perlfaqs {  my ($self, $found_things, $pod) = @_;  local $_;  for my $file (@$found_things) {    my $perlfaq = fileparse($file, qr/\.pod/);    open(INFAQ, &#39;&lt;&#39;, $file) or die &quot;$file: $!\n&quot;;    my $faqnum = sprintf &#39;%02d&#39;, 1;    while (&lt;INFAQ&gt;) {      if (/^=head2\s/) {        $show_faqnums and substr($_, 7, 0, &quot;[$perlfaq - $faqnum]  &quot;);        push @$pod, &quot;$_\n&quot;;        $faqnum++;      }    }    close(INFAQ);  }  return;}sub Pod::Perldoc::page {  my ($self, $output) = @_;  open(TMP, &#39;&lt;&#39;, $output) or die &quot;$output: $!\n&quot;;  local $_;  while (&lt;TMP&gt;) {    s/^\s+//;    print or die &quot;$!\n&quot;;  }  close TMP or die &quot;$output: $!\n&quot;;  $self-&gt;unlink_if_temp_file($output);  return;}Pod::Perldoc-&gt;run();&lt;/pre&gt;
    </description>
</item>

        

<item>
    <title>Reaped: (NodeReaper)</title>
    <link>http://prlmnks.org/html/573542.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/573542.html</guid>

    <description>
        This node was taken out by the &lt;a href=&quot;/out/node/NodeReaper&quot;&gt;NodeReaper&lt;/a&gt; on &lt;a href=&quot;/out/localtime/2006-09-18 10-04-01&quot;&gt;2006-09-18 10-04-01&lt;/a&gt;&lt;BR&gt;Reason:  &amp;#91;&lt;a href=&quot;/out/node/davorg&quot;&gt;davorg&lt;/a&gt;]: reap&lt;p&gt;You may view &lt;a href=&quot;/out/href/?node=Visit%20Reaped%20Nodes&amp;amp;nodenum=573542&quot;&gt;the original node and the consideration vote tally&lt;/a&gt;.&lt;/p&gt;
    </description>
</item>

        

<item>
    <title>quick startup time profiler (merlyn)</title>
    <link>http://prlmnks.org/html/573417.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/573417.html</guid>

    <description>
        I was curious about the startup time of my program, so I wanted to figure out how many lines of code were being loaded and how long that was taking.&lt;p&gt;So I created &quot;MM.pm&quot;, and loaded my top-level module with &lt;tt class=&quot;inline_code&quot;&gt;perl -MMM -MMy::Module -e0&lt;/tt&gt;.  MM shows real time, and cpu for user, system, child user, and child system, and then opens each of the included modules and gives a line count, including a total linecount.&lt;pre class=&quot;block_code&quot;&gt;package MM;my @times = (time, times);END {  warn sprintf(&quot;real %d, user %.2g, sys %.2g, cuser %.2g, csys %.2g\n&quot;,       map { $_ - shift @times } time, times);  local *ARGV;  @ARGV = sort values %INC;  my $sum = 0;  while (&lt;&gt;) {    next unless eof;    warn &quot;$ARGV: $.\n&quot;;    $sum += $.;    close ARGV;  }  warn &quot;total: $sum\n&quot;;}1;&lt;/pre&gt;
    </description>
</item>

        

<item>
    <title>z-charcoal-video-converter (zentara)</title>
    <link>http://prlmnks.org/html/573230.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/573230.html</guid>

    <description>
        Time for Friday afternoon fun!!&lt;p&gt;Ever want to make one of those animated videos, like are currently popular on american tv, that are obviously recorded, yet appear to be drawn?  Here is a 1 shot script to do it. A morepowerful program to do this is &lt;a href=http://lives.sourceforge.net/&gt; Lives &lt;/a&gt;&lt;p&gt;A sample video is at &lt;a href=http://zentara.net/colors.flv&gt; a sample from youtube &lt;/a&gt; and it&#39;s &lt;a href=http://zentara.net/colors.avi&gt; charcoal version &lt;/a&gt;.&lt;pre class=&quot;block_code&quot;&gt;#!/usr/bin/perluse warnings;use strict;use File::Path qw(rmtree);use Image::Magick;# Usage: $0 colors.flv  OR  $0 r# The r option will skip ripping and recombine# the contents of the riptemp-$base subdir.# This allows you to manually edit individual files.# If more than 2 riptemp dirs are present, the first# in a dirlist will be used. So.... work on 1 at a time# in their own directories. This is just a snippet. :-)# I admit, that the Lives (Linux Video Editing System)# at http://lives.sourceforge.net/# is much more powerful than this. Check it out, and # it&#39;s &quot;smogrify&quot; perl script.... which is it&#39;s workhorse. $|++;my $video = shift || &#39;colors.flv&#39;;my $base;if($video eq &#39;r&#39;){ recombine();   }else{       $video =~ /^(.+)(\.\w+)$/;       $base = $1;}#rip to jpg&#39;s and audio#will make it&#39;s own temp dirmy @moptions =( &#39;mplayer&#39;,                &#39;-osdlevel&#39;, 0,                &#39;-vo&#39;, &quot;jpeg:quality=100:outdir=riptemp-$base:maxfiles=2000&quot;,                &#39;-noframedrop&#39;,  #important for quality&#39;-ao&#39;, &quot;pcm:file=$base.wav&quot;,$video,);system(@moptions);opendir my $dh, &quot;riptemp-$base&quot; or die &quot;Error: $!\n&quot;;my @files = grep !/^\.\.?$/, readdir $dh;closedir $dh;my $p = new Image::Magick; #only make one and reusemy $max = scalar @files;my $count = 0;foreach my $file ( @files ) {  # operate on jpgs for effects  $count++;  print &quot;\rprocessing file $count/$max&quot;;  $p-&gt;Read(&quot;riptemp-$base/$file&quot;);  $p-&gt;Negate();  $p-&gt;Charcoal(&#39;0x1&#39;);  $p-&gt;Write(&quot;riptemp-$base/$file&quot;);  undef @$p;  #clear out object data}print &quot;\n\nDone effects processing\n\n&quot;;###################### recombinerecombine();#ask to keep clips or notprint &quot;\n\nDone! Delete temp clips? (n/y) Defaults to n\n&quot;;my $return = &lt;&gt;;if($return =~ /^[yY].*$/){  rmtree(&quot;riptemp-$base&quot;, 0, 1); # verbose report, and ignore undeleteables }else{exit}#####################################################################sub recombine{opendir my $dh, &#39;.&#39; or die &quot;Error: $!\n&quot;;my @files = grep !/^\.\.?$/, readdir $dh;@files = grep /^riptemp-(.*)$/, @files;closedir $dh;my $dir = $files[0];$dir =~ /^riptemp-(.*)$/;my $base = $1;#print &quot;$dir\t$base\n&quot;;my @moptions =( &#39;mencoder&#39;,                &quot;mf://$dir/*.jpg&quot;,                &#39;-mf&#39;, &#39;fps=29.97&#39;, #NTSC tv video rate in                 &#39;-audiofile&#39;, &quot;$base.wav&quot;, &#39;-srate&#39;, 22050,&#39;-o&#39;, &quot;$base-char.avi&quot;,                &#39;-ovc&#39;, &#39;lavc&#39;,&#39;-lavcopts&#39;, &#39;vcodec=mpeg4:vbitrate=100&#39;,&#39;-oac&#39;, &#39;mp3lame&#39;,#&#39;-audio-delay&#39;, 0.2, #adjust for audio syncing problems);system(@moptions);}######################################################################3&lt;/pre&gt;
    </description>
</item>

        

<item>
    <title>Find names of an object or class&#39;s methods (GrandFather)</title>
    <link>http://prlmnks.org/html/572662.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/572662.html</guid>

    <description>
        &lt;p&gt;Given an object or class name and an optional member name prefix &lt;tt class=&quot;inline_code&quot;&gt;MembersMatching&lt;/tt&gt; returns a list of matching member names for the class.&lt;/p&gt;&lt;p&gt;The sample prints:&lt;/p&gt;&lt;pre class=&quot;block_code&quot;&gt;getoptions, configure, new&lt;/pre&gt;&lt;p&gt;Note: this ignores inheritance.&lt;/p&gt;&lt;p&gt;Updated to return only methods&lt;/p&gt;&lt;p&gt;Updated following advice from [ysth]&lt;/p&gt;&lt;pre class=&quot;block_code&quot;&gt;use strict;use warnings;use Getopt::Long;my $p = new Getopt::Long::Parser;print join &#39;, &#39;, MembersMatching($p, &#39;[a-z_]&#39;);sub MembersMatching {    my ($object, $prefix) = @_;        $object = ref $object if ref $object;    $prefix ||= &#39;&#39;;        no strict;    no strict;    return grep {/^$prefix/ &amp;&amp; exists &amp;{&quot;${object}::$_&quot;}} keys %{&quot;${object}::&quot;};}&lt;/pre&gt;
    </description>
</item>

        

<item>
    <title>Reaped: test (NodeReaper)</title>
    <link>http://prlmnks.org/html/572143.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/572143.html</guid>

    <description>
        This node was taken out by the &lt;a href=&quot;/out/node/NodeReaper&quot;&gt;NodeReaper&lt;/a&gt; on &lt;a href=&quot;/out/localtime/2006-09-09 10-16-26&quot;&gt;2006-09-09 10-16-26&lt;/a&gt;&lt;BR&gt;Reason:  &amp;#91;&lt;a href=&quot;/out/node/Albannach&quot;&gt;Albannach&lt;/a&gt;]: delete - no content&lt;p&gt;You may view &lt;a href=&quot;/out/href/?node=Visit%20Reaped%20Nodes&amp;amp;nodenum=572143&quot;&gt;the original node and the consideration vote tally&lt;/a&gt;.&lt;/p&gt;
    </description>
</item>

        

<item>
    <title>Retrieve list of used modules and their version numbers (GrandFather)</title>
    <link>http://prlmnks.org/html/571662.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/571662.html</guid>

    <description>
        The first part of the snippet goes at the top of your script.&lt;/p&gt;&lt;p&gt;The second part goes where you want to list the modules and versions. Sample output looks like:&lt;/p&gt;&lt;pre class=&quot;block_code&quot;&gt;Tk 804.027Tk::Event 4.015Tk::Event::IO 4.008AutoLoader 5.60DynaLoader 1.05Tk::Submethods 4.004Encode::Unicode 1.40&lt;/pre&gt;&lt;pre class=&quot;block_code&quot;&gt;use strict;use warnings;BEGIN {our @usedModules; unshift @INC, sub {push @usedModules, [@_]; return undef;}}our @usedModules;...my $versions = &#39;&#39;;for (@usedModules) {   my $name = $_-&gt;[1];   $name =~ s/\..*//;   $name =~ s|[\\/]|::|g;      my $version = eval{eval &quot;\$$name\::VERSION&quot;};   $versions .= &quot;$name \t$version\n&quot; if defined $version;}print $versions;&lt;/pre&gt;
    </description>
</item>

        

<item>
    <title>Tk Patio/Office layout designer (zentara)</title>
    <link>http://prlmnks.org/html/571493.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/571493.html</guid>

    <description>
        This is an attempt to improve on [id://570950]. After some experimentation with rotations, and collision detection, I finally came to the conclusion that collision detection wasn&#39;t robust enough. Why? First, the overlap detection only works on rectangular regions. This prevents circular pavers, and triangular cut pavers from working with collision detection. Second, the amount of computation needed to detect overlaps on each incremental move, sometimes caused &quot;lack of smooth dragging and rotating&quot;. So bye-bye collision detection.  &lt;p&gt;I did add arbitrary rotation in 15 degree increments, and added circles.&lt;p&gt;This probably could be useful in planning a patio, office layout, or even a garden. &lt;p&gt;One note of interest, is that to get arbitrary rotations, rectangles and triangles, must be plotted as polygons, where each vertex is defined.  See Ala Qumsieh&#39;s [cpan://Tk-RotCanvas] &lt;pre class=&quot;block_code&quot;&gt;#!/usr/bin/perluse warnings;use strict;use Tk;# USAGE: $0 x-dimension y-dimension# in meters e.g. $0 8.65 4.1# Your going to lay a patio using brand of precast concrete # &quot;stone effect&quot; pavers that come in a range of sizes:# in centimeters to make screen sizing easier, 1 cm per pixel# we need the rectangles to be created as polygons because #  rotations of arbitrary degrees need every vertex identified# r for rectangular, c for circlesmy %ss = (  &#39;a&#39; =&gt; [30,30,&#39;hotpink&#39;,&#39;r&#39;],   &#39;b&#39; =&gt; [45,30,&#39;red&#39;,&#39;r&#39;],   &#39;c&#39; =&gt; [45,45,&#39;lightblue&#39;,&#39;r&#39;],   &#39;d&#39; =&gt; [60,45,&#39;pink&#39;,&#39;r&#39;],   &#39;e&#39; =&gt; [60,60,&#39;grey70&#39;,&#39;r&#39;],   &#39;f&#39; =&gt; [60,30,&#39;lightgreen&#39;,&#39;r&#39;],   &#39;g&#39; =&gt; [75,60,&#39;wheat1&#39;,&#39;r&#39;],   &#39;h&#39; =&gt; [75,75,&#39;khaki&#39;,&#39;r&#39;],   &#39;i&#39; =&gt; [90,60,&#39;plum1&#39;,&#39;r&#39;],   &#39;j&#39; =&gt; [30,30,&#39;lightsteelblue&#39;,&#39;c&#39;],  &#39;k&#39; =&gt; [45,45,&#39;lightsteelblue&#39;,&#39;c&#39;],  &#39;l&#39; =&gt; [60,60,&#39;lightsteelblue&#39;,&#39;c&#39;],  &#39;m&#39; =&gt; [90,90,&#39;lightsteelblue&#39;,&#39;c&#39;],);# print $ss{&#39;a&#39;}-&gt;[0] , $ss{&#39;a&#39;}-&gt;[1], $ss{&#39;a&#39;}-&gt;[2],&quot;\n&quot;;# print @{ $ss{&#39;a&#39;} },&quot;\n&quot;;#The size of the patio as input can be &#39;rounded up&#39; in either #or both dimensions to the next of the greatest #common divisor (GCD) of the list of sizes. #(This puts all cuts to be made in the actual #patio at one of the four edges). #For example. The GCD of the 9 sizes above is 150mm. #This forms a minimum grid for the layout. If the patio size #entered was 8.65 x 4.1, then this would be round up to# my $patio_xin = 8.65;# my $patio_yin = 4.1;# my $patio_x =  0.15 * ( 1 + int( $patio_xin / 0.15 ) ); # my $patio_y =  0.15 * ( 1 + int( $patio_yin / 0.15 ) );# print &quot;$patio_x  $patio_y\n&quot;; # 8.7 x 4.2my $patio_xin = shift || 8.65;my $patio_yin = shift || 4.1;my $patio_x =  0.15 * ( 1 + int( $patio_xin / 0.15 ) ); my $patio_y =  0.15 * ( 1 + int( $patio_yin / 0.15 ) );my $dx;   #globals used for draggingmy $dy;my $ptag;my $patio;my $mw = MainWindow-&gt;new;$mw-&gt;fontCreate(&#39;big&#39;,   -family=&gt;&#39;arial&#39;,   -weight=&gt;&#39;bold&#39;,   -size=&gt;int(-18*18/14));my $topframe = $mw-&gt;Frame(-bg=&gt;&#39;black&#39;)-&gt;pack(-fill=&gt;&#39;x&#39;);$topframe-&gt;Label(-text=&gt;&quot;X-Y = $patio_x - $patio_y (rounded)&quot;,                 -bg =&gt; &#39;black&#39;, -fg =&gt; &#39;lightblue&#39;, -font =&gt; &#39;big&#39;, )-&gt;pack(-side=&gt;&#39;left&#39;);$topframe-&gt;Label(-text=&gt;&#39;  &#39;,                 -bg =&gt; &#39;black&#39;, )-&gt;pack(-side=&gt;&#39;left&#39;);$topframe-&gt;Label(-text=&gt;&#39;Drag pavers with left button, rotate them with a right (or shift-right)click&#39;,                 -bg =&gt; &#39;black&#39;, -fg =&gt; &#39;lightgreen&#39;, )-&gt;pack(-side=&gt;&#39;left&#39;); my $S_canvas = $mw-&gt;Scrolled(&#39;Canvas&#39;,                -width =&gt; 600, -height =&gt; 600,                -bg =&gt; &#39;grey40&#39;,-borderwidth =&gt; 0, -relief =&gt; &#39;sunken&#39;,-scrollbars =&gt; &#39;osoe&#39;,-scrollregion =&gt; [ 0, 0, 1000, 1000 ],   )-&gt;pack(-expand =&gt; 1, -fill =&gt;&#39;both&#39;);my $canvas = $S_canvas-&gt;Subwidget(&#39;scrolled&#39;);my $closebutton = $mw-&gt;Button(-text =&gt; &#39;Exit&#39;, -command =&gt; sub{Tk::exit(0)})               -&gt;pack; my $x0 = 20; #slight offsetmy @count = reverse(1..99);foreach my $num (@count){foreach my $paver (&#39;a&#39;..&#39;m&#39;){    my($x,$y,$color,$type) = @{ $ss{ $paver } };#    print &quot;$x,$y,$color,$type\n&quot;;#   $canvas-&gt;createRectangle($x0, 0, $x0 + $x, $y,    if($type eq &#39;r&#39;){       $canvas-&gt;createPolygon( $x0, 0,                              $x0 + $x, 0,     $x0 + $x, $y,      $x0, $y,     $x0, 0,      -fill =&gt; $color,     -tags =&gt; [&#39;move&#39;, &quot;$paver$num&quot;.&#39;p&#39;, &#39;paver&#39;],      -width =&gt; 0, );    }   if($type eq &#39;c&#39;){       $canvas-&gt;createOval( $x0, 0,                              $x0 + $x, $y,     -fill =&gt; $color,    -tags =&gt; [&#39;move&#39;, &quot;$paver$num&quot;.&#39;p&#39;, &#39;paver&#39;],     -width =&gt; 0, );    }    $canvas-&gt;createText($x0 + ($x/2)  , $y/2,           -anchor=&gt;&#39;center&#39;,   -fill =&gt; &#39;black&#39;,           -text =&gt; &quot;   $paver$num\n&quot;.($ss{$paver}-&gt;[0]).&#39;x&#39;.($ss{$paver}-&gt;[1]),   -tags =&gt; [&#39;move&#39;, &quot;$paver$num&quot;.&#39;t&#39;, &#39;paver&#39;],  );    $x0 += $x; }$x0 = 20;}# rectangle to simulate patio for dragging pavers to$canvas-&gt;createRectangle(15, 120, 15+$patio_x*100, 120 + $patio_y*100,                              -fill =&gt; &#39;black&#39;,     -outline =&gt; &#39;white&#39;,     -width =&gt; 2,     -tags =&gt; [&#39;patio&#39;],     );$canvas-&gt;lower(&#39;patio&#39;, &#39;paver&#39;);$canvas-&gt;configure(-width =&gt; $patio_x * 100 + 20,                    -height=&gt; $patio_y * 100 + 130);$canvas-&gt;configure(-scrollregion =&gt; [0,0,$patio_x * 100 + 120,$patio_y * 100 + 250]);$canvas-&gt;bind(&#39;move&#39;, &#39;&lt;1&gt;&#39;, sub {&amp;mobileStart();});$canvas-&gt;bind(&#39;move&#39;, &#39;&lt;B1-Motion&gt;&#39;, sub {&amp;mobileMove();});$canvas-&gt;bind(&#39;move&#39;, &#39;&lt;ButtonRelease-1&gt;&#39;, sub {&amp;mobileStop();});$canvas-&gt;bind(&#39;paver&#39;,&#39;&lt;3&gt;&#39;, sub {                       my(@tags) = $canvas-&gt;gettags(&quot;current&quot;);                       @tags = grep{/^\w{1}\d+[pt]$/} @tags;                              chop $tags[0]; #pull off t or p                       my $ptag = $tags[0];       &amp;rotate_poly($ptag,-15,undef,undef);  });$canvas-&gt;bind(&#39;paver&#39;,&#39;&lt;Shift-3&gt;&#39;, sub {                       my(@tags) = $canvas-&gt;gettags(&quot;current&quot;);                       @tags = grep{/^\w{1}\d+[pt]$/} @tags;                              chop $tags[0]; #pull off t or p                       my $ptag = $tags[0];       &amp;rotate_poly($ptag,15,undef,undef);  });#postscript save$topframe-&gt;Button(    -text    =&gt; &quot;Save as postscript&quot;,    -command =&gt; [sub {         $canvas-&gt;update;         my @capture=();         my ($x0,$y0,$x1,$y1)=$canvas-&gt;bbox(&#39;all&#39;);         $y0 = 120; #lop off paver stacks @capture=(&#39;-x&#39;=&gt;$x0,&#39;-y&#39;=&gt;$y0,-height=&gt;$y1-$y0,-width=&gt;$x1-$x0);         my $filename = $patio_x.&#39;-&#39;.$patio_y.&#39;--&#39;.time.&#39;.ps&#39;; $canvas-&gt;postscript(-colormode=&gt;&#39;color&#39;,                              -file=&gt; $filename,      -rotate=&gt;0,      -width=&gt;$patio_x + 100,      -height=&gt;$patio_y + 100,           @capture);                                     }   ]  )-&gt;pack;MainLoop;#####################################################sub mobileStart {      my $ev = $canvas-&gt;XEvent;      ($dx, $dy) = (0 - $ev-&gt;x, 0 - $ev-&gt;y);      my(@tags) = $canvas-&gt;gettags(&quot;current&quot;);      @tags = grep{/^\w{1}\d+[pt]$/} @tags;             chop $tags[0]; #pull off t or p      $ptag = $tags[0];     # print &quot;$ptag\n&quot;;      $canvas-&gt;raise($ptag.&#39;p&#39;);      $canvas-&gt;raise($ptag.&#39;t&#39;); #keep text showing#     print &quot;START MOVE-&gt;  $dx  $dy\n&quot;;}############################################################sub mobileMove {            return if ($ptag eq &#39;&#39;);      my $ev = $canvas-&gt;XEvent;      my $y = $ev-&gt;y;      foreach($ptag.&#39;p&#39;, $ptag.&#39;t&#39;){         $canvas-&gt;move($_, $ev-&gt;x + $dx, $ev-&gt;y +$dy);        }          ($dx, $dy) = (0 - $ev-&gt;x, 0 - $ev-&gt;y);}##############################################################sub mobileStop{ $ptag = &#39;&#39; }#############################################################sub rotate_poly {    my ($tag, $angle, $midx, $midy) = @_;    #taken from Ala Qumsieh&#39;s ROTCanvas module        $tag = $tag.&#39;p&#39;;    return if($canvas-&gt;type($tag) eq &#39;oval&#39;);        # Get the old coordinates.    my @coords_in = $canvas-&gt;coords($tag);    my @old = @coords_in;             # Get the center of the poly. We use this to translate the    # above coords back to the origin, and then rotate about    # the origin, then translate back. (old)    ($midx, $midy) = _get_CM(@coords_in) unless defined $midx;    my @new;    # Precalculate the sin/cos of the angle, since we&#39;ll call    # them a few times.    my $rad = 3.1416*$angle/180;    my $sin = sin $rad;    my $cos = cos $rad;    # Calculate the new coordinates of the line.    while (my ($x, $y) = splice @coords_in, 0, 2) {my $x1 = $x - $midx;my $y1 = $y - $midy;push @new =&gt; $midx + ($x1 * $cos - $y1 * $sin);push @new =&gt; $midy + ($x1 * $sin + $y1 * $cos);    }    # Redraw the poly.    $canvas-&gt;coords($tag, @new); }################################################################## This sub finds the center of mass of a polygon.# I grabbed the algorithm somewhere from the web.# I grabbed it from Ala Qumsieh&#39;s RotCanvas :-)sub _get_CM {    my ($x, $y, $area);    my $i = 0;    while ($i &lt; $#_) {my $x0 = $_[$i];my $y0 = $_[$i+1];my ($x1, $y1);if ($i+2 &gt; $#_) {    $x1 = $_[0];    $y1 = $_[1];} else {    $x1 = $_[$i+2];    $y1 = $_[$i+3];}$i += 2;my $a1 = 0.5*($x0 + $x1);my $a2 = ($x0**2 + $x0*$x1 + $x1**2)/6;my $a3 = ($x0*$y1 + $y0*$x1 + 2*($x1*$y1 + $x0*$y0))/6;my $b0 = $y1 - $y0;$area += $a1 * $b0;$x    += $a2 * $b0;$y    += $a3 * $b0;    }    return split &#39; &#39;, sprintf &quot;%.0f %0.f&quot; =&gt; $x/$area, $y/$area;}####################################################################&lt;/pre&gt;
    </description>
</item>

        

<item>
    <title>Reaped: parse log (NodeReaper)</title>
    <link>http://prlmnks.org/html/571411.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/571411.html</guid>

    <description>
        This node was taken out by the &lt;a href=&quot;/out/node/NodeReaper&quot;&gt;NodeReaper&lt;/a&gt; on &lt;a href=&quot;/out/localtime/2006-09-06 06-38-42&quot;&gt;2006-09-06 06-38-42&lt;/a&gt;&lt;BR&gt;Reason:  &amp;#91;&lt;a href=&quot;/out/node/GrandFather&quot;&gt;GrandFather&lt;/a&gt;]: reap - empty node&lt;p&gt;You may view &lt;a href=&quot;/out/href/?node=Visit%20Reaped%20Nodes&amp;amp;nodenum=571411&quot;&gt;the original node and the consideration vote tally&lt;/a&gt;.&lt;/p&gt;
    </description>
</item>

        

<item>
    <title>HTML to text (fatalserpent)</title>
    <link>http://prlmnks.org/html/571183.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/571183.html</guid>

    <description>
        A one(half) line code for HTML to text conversion.&lt;pre class=&quot;block_code&quot;&gt;perl -pe &#39;s/&lt;.*?&gt;//g&#39;&lt;/pre&gt;EDIT: Forgot the dot... lolzerz EDITEDIT:OMG, I forgot the ? too... heh heh heh *yawn* I&#39;m too tired to be posting code on PM (also I&#39;m not a very good perl scripter, but this one was just repeated typos)
    </description>
</item>

        

<item>
    <title>Reaped: Perl (NodeReaper)</title>
    <link>http://prlmnks.org/html/571113.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/571113.html</guid>

    <description>
        This node was taken out by the &lt;a href=&quot;/out/node/NodeReaper&quot;&gt;NodeReaper&lt;/a&gt; on &lt;a href=&quot;/out/localtime/2006-09-04 15-12-37&quot;&gt;2006-09-04 15-12-37&lt;/a&gt;&lt;BR&gt;Reason:  &amp;#91;&lt;a href=&quot;/out/node/tye&quot;&gt;tye&lt;/a&gt;]: (reap) Failed search attempt?&lt;p&gt;You may view &lt;a href=&quot;/out/href/?node=Visit%20Reaped%20Nodes&amp;amp;nodenum=571113&quot;&gt;the original node and the consideration vote tally&lt;/a&gt;.&lt;/p&gt;
    </description>
</item>

        

<item>
    <title>Find common elements in a list of arrays (GrandFather)</title>
    <link>http://prlmnks.org/html/570973.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/570973.html</guid>

    <description>
        &lt;p&gt;The snippet finds all the common elements across a list of arrays.&lt;/p&gt;&lt;p&gt;It is similar to List::Compare&#39;s get_intersection except that it returns all the common elements, rather than a list of the unique common elements:&lt;/p&gt;&lt;pre class=&quot;block_code&quot;&gt;findCommon ([1, 2, 2], [2, 2, 3]);&lt;/pre&gt;&lt;p&gt;would return &lt;tt class=&quot;inline_code&quot;&gt;(2, 2)&lt;/tt&gt; for example.&lt;/p&gt;&lt;p&gt;Gotchas&lt;/p&gt;&lt;ul&gt;&lt;li&gt;findCommon expects the lists to be sorted&lt;/li&gt;&lt;li&gt;findCommon destroys the lists passed in&lt;/li&gt;&lt;/ul&gt;&lt;p&gt;Note that Storable&#39;s dclone can be used to efficiently copy the lists if required.&lt;/p&gt;&lt;pre class=&quot;block_code&quot;&gt;sub findCommon {    my @lists = @_;    my @common;        while (@lists == grep {@$_} @lists) {        my %hits;                $hits{$_-&gt;[0]}++ for @lists;                my $least = (sort keys %hits)[0];                push @common, $least if $hits{$least} == @lists;        $_-&gt;[0] eq $least &amp;&amp; shift @$_ for @lists;    }        return @common;}&lt;/pre&gt;
    </description>
</item>

        

<item>
    <title>Tk-front-end-to YouTube.com videos (zentara)</title>
    <link>http://prlmnks.org/html/570873.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/570873.html</guid>

    <description>
        In an attempt to merge [id://570467] and my Tk front end to Mplayer at [id://417164], here is a YouTube.com sampler. It is not perfect. The categories are hard coded in, and it only gets the first page of each category( maybe 10 videos each)&lt;p&gt;Also I hacked a quick Listbox widget to display the retreived files. But since I used  a thread to download, I needed to update the listbox every 10 seconds manually, which can be annoying if you try to select a file right at update time.&lt;p&gt;Anyways, it will work on linux (X11) only, and you need an mplayer that can play .flv files.&lt;p&gt;I creatively named the downloaded files, by concating the titles and flv filename, so you can tell what they are more easily.&lt;p&gt;Start the app, if any flv files are present in the working dir, they will be listed. Otherwise, press the Select Catagories button, and select 1 or more categories to sample. Then the downloader will get the videos in the background. &lt;pre class=&quot;block_code&quot;&gt;#!/usr/bin/perl -wuse strict;use Tk;require Tk::Pane;use Proc::Killfam;                                                                        use Tk::ROText;use LWP::UserAgent;use LWP::Simple;use HTML::LinkExtor;use URI::URL;use threads;use threads::shared;#  it will work on linux (X11) only, and you need an mplayer # that can play .flv files.#I creatively named the downloaded files, by concating the # titles and flv filename, so you can tell what they are more # easily.# Start the app, if any flv files are present in the working dir, # they will be listed. Otherwise, press the Select Catagories # button, and select 1 or more categories to sample. Then the # downloader will get the videos in the background. # must setup thread code before any Tk code is used# to avoid Tk thread-safety problemsmy $thread_die : shared;my $thread_go : shared;my @selected : shared;my @ready : shared;$thread_die = 0;$thread_go = 0;@selected = ();@ready = ();my $thread = threads-&gt;new( \&amp;work );###################################################                                                                                          $|++;my @links;  #a global for Link extractor, funky callback hack my $ua = LWP::UserAgent-&gt;new();my @selected_cats =();my @ready_lb; #local non-thread copy of @ready to prevent              #Tk from segfaulting$SIG{INT} = sub { &amp;close_it_up };$SIG{PIPE} = &#39;IGNORE&#39;;my $mpg_in = shift || &#39;&#39;; #mpg to play from command line# needs an init.mpg which will be created if you# don&#39;t supply oneif( ! -e &#39;init.mpg&#39;){ &amp;make_init}#setup local files to play  @ready = &lt;*.flv&gt;;#newly downloaded files will be pushed onto @ready#if there are no .flv files in the dir, the first completed#download will play upon arrival@ready_lb = @ready;my $cur_play;my $title;my $playing = 0; #flag used in auto-playing first completed downloadmy $timer;my $timer1;my $mw = MainWindow-&gt;new(-background =&gt;&#39;black&#39;);$mw-&gt;geometry(&#39;530x650+20+30&#39;);$mw-&gt;Tk::bind(&quot;&lt;q&gt;&quot;, sub{&amp;close_it_up});$mw-&gt;Tk::bind(&quot;&lt;Escape&gt;&quot;, sub{&amp;close_it_up});my $cframe1 = $mw-&gt;Frame(-background =&gt;&#39;black&#39;)            -&gt;pack( -fill =&gt;&#39;x&#39;);my $cframe2 = $mw-&gt;Frame(-background =&gt;&#39;black&#39;)            -&gt;pack( -fill =&gt;&#39;x&#39;);my $canv = $mw-&gt;Scrolled(&#39;Canvas&#39;,     -bg =&gt; &#39;black&#39;,     -borderwidth =&gt; 0,     -highlightthickness =&gt; 0,     -relief =&gt; &#39;sunken&#39;,     -width =&gt;  500,     -height =&gt; 400,     -scrollregion=&gt;[0,0,500,400],                                                                  -scrollbars=&gt;&#39;osoe&#39;,        )-&gt;pack();my $contWidth = 500;my $contHeight = 400;## this Frame is needed for including the window in Tk::Canvasmy $Container = $canv-&gt;Frame(-container =&gt; 1);my $xtid = $Container-&gt;id();# converting the id from HEX to decimal as xterm requires a decimal Idmy ($xtId) = sprintf hex $xtid;my $dcontitem = $canv-&gt;createWindow(10,10,   -anchor=&gt;&#39;nw&#39;,   -window =&gt; $Container,   -width =&gt; $contWidth,   -height =&gt; $contHeight,   -state =&gt; &#39;hidden&#39;,   -tags =&gt; [&#39;viewport&#39;],   );my $pid;my @options = (  &#39;-slave&#39;,&#39;-loop 0&#39;, &#39;-zoom&#39;,                 &quot;-x $contWidth&quot;, &quot;-y $contHeight&quot;, &#39;-really-quiet&#39;,  &quot;-wid $xtId&quot;,       );my $loadu_but = $cframe1-&gt;Button(-text =&gt; &#39;Select Category&#39;,              -padx =&gt; 0,              -command =&gt; sub{         my $url = &amp;get_url;         })-&gt;pack(-side =&gt;&#39;left&#39;,-padx=&gt;10 );$cframe1-&gt;Button(-text =&gt; &quot;Exit&quot;,              -padx =&gt; 0,             -command =&gt; [sub{&amp;close_it_up}] )     -&gt;pack(-side=&gt;&#39;right&#39;, -padx =&gt;10 );$cframe1-&gt;Button(-text =&gt; &quot;Stop Download&quot;,              -padx =&gt; 0,             -command =&gt; sub{ $thread_go = 0;                     $timer1-&gt;cancel; #stop updating list                        } )     -&gt;pack(-side=&gt;&#39;right&#39;, -padx =&gt;10 );my $sound = 1;                                                                  $cframe1-&gt;Checkbutton(                                                                                 -text =&gt; &#39;Sound&#39;,                                                       -background =&gt; &#39;lightblue&#39;,-variable =&gt; \$sound,                                                               -command  =&gt; \&amp;set_sound,                                                                  )-&gt;pack(-fill =&gt;&#39;y&#39; );                                                                                  $cframe2-&gt;Label(-text =&gt; &#39;SpaceBar-&gt;Pause    q or esc -&gt; exit     left and right arrow keys navigate&#39;,                -background =&gt; &#39;black&#39;,-foreground =&gt; &#39;lightgreen&#39;,                 )-&gt;pack(-expand=&gt;1 );$cframe2-&gt;Label( -textvariable =&gt; \$title ,                -background =&gt; &#39;black&#39;,-foreground =&gt; &#39;lightblue&#39;,                 )-&gt;pack(-expand=&gt;1 );&amp;start_player;if($mpg_in ne &#39;&#39;){ &amp;play($mpg_in)}$mw-&gt;Label( -text =&gt; &#39;Left Click Select...Right Click Play&#39;,                -background =&gt; &#39;black&#39;,-foreground =&gt; &#39;green&#39;,                 )-&gt;pack(-fill =&gt; &#39;x&#39;,-expand =&gt; 1 );my $lb = $mw-&gt;Scrolled(&#39;Listbox&#39;,              -scrollbars=&gt;&#39;osow&#39;,             -listvariable =&gt; \@ready_lb,             -background =&gt; &#39;white&#39;,     )-&gt;pack(-fill =&gt; &#39;x&#39;,-expand=&gt;1);$lb-&gt;bind( &#39;&lt;ButtonPress-3&gt;&#39;,  sub{        my $file = $lb-&gt;get($lb-&gt;curselection);        $playing = 1; #set flag that we are playing a local file&amp;play($file);    });MainLoop();#########################################################sub get_url{my %cats = (1 =&gt; &#39;Arts &amp;Animation&#39;,2 =&gt; &#39;Autos &amp; Vehicles&#39;,23 =&gt; &#39;Comedy&#39;,24 =&gt; &#39;Entertainment&#39;,10 =&gt; &#39;Music&#39;,25 =&gt; &#39;News &amp; Blogs&#39;,22 =&gt; &#39;People&#39;,15 =&gt; &#39;Pets &amp; Animals&#39;,26 =&gt; &#39;Science &amp; Technology&#39;,17 =&gt; &#39;Sports&#39;,19 =&gt; &#39;Travel &amp; Places&#39;,20 =&gt; &#39;Video Games&#39;);my $url_top = &quot;http://youtube.com/categories_portal&quot;;    # for instance@links = &amp;get_links( $url_top );# http://youtube.com/categories_portal?c=1&amp;e=1my $lead = &#39;http://youtube.com/categories_portal?c=&#39;;my $rx = qr/\Q$lead\E(.*)/;@links = grep{/$rx/} @links;#remove dups@links = keys %{{map{$_,1} @links}};my %result_list =();#sort the links according to categorymy $rx1 = qr/\Q$lead\E(\d+).*/;   foreach my $link (@links){   $link =~ /$rx1/;   my $cat = $1;             push @{ $result_list{ $cat } }, $link;}my @hyperlinks =();foreach my $key (keys %result_list){#       print $cats{$key},&quot;\n&quot;;#       print join( &quot;\n&quot;, @{ $result_list{ $key } } ), &quot;\n\n\n&quot;;      push @hyperlinks, &quot;$cats{$key}\n&quot;;           foreach( @{ $result_list{ $key } } ){         push @hyperlinks, &quot;$_\n&quot;;             }     }#popupmy $tl = MainWindow-&gt;new();$tl-&gt;title(&quot;Select YouTube Categories&quot;);$tl-&gt;fontCreate(&#39;big&#39;,   -family=&gt;&#39;arial&#39;,  -weight=&gt;&#39;bold&#39;,  -size=&gt;int(-18*18/14));my $t = $tl-&gt;Scrolled(&#39;ROText&#39;,             -width =&gt; 80,     -height =&gt; 30,     -background =&gt; &#39;white&#39;,     )-&gt;pack();my $ebutton = $tl-&gt;Button(-text =&gt;&#39;Done Selecting&#39;,            -command =&gt; sub{                $tl-&gt;destroy;                #print &quot;@selected_cats\n&quot;;                #now start to process links and download#videos in the work thread            &amp;start_downloads;        })-&gt;pack();#add colors$t-&gt;tagConfigure( &#39;tag1&#39;, -foreground =&gt; &#39;red&#39;, -font =&gt; &#39;big&#39; );my $tag = &quot;tag000&quot;;foreach (@hyperlinks) {    chomp;    my @res = split (/(http:\S+)/);    foreach (@res) {        if (/(http:\S+)/) {            $t-&gt;insert( &#39;end&#39;, $_, $tag );            $t-&gt;tagConfigure( $tag, -foreground =&gt; &#39;blue&#39; );            $t-&gt;tagBind( $tag,                &#39;&lt;Any-Enter&gt;&#39; =&gt; [ \&amp;manipulate_link, $tag, &#39;raised&#39;, &#39;hand2&#39; ]            );            $t-&gt;tagBind( $tag,                &#39;&lt;Any-Leave&gt;&#39; =&gt; [ \&amp;manipulate_link, $tag, &#39;flat&#39;, &#39;xterm&#39; ] );            $t-&gt;tagBind( $tag,                &#39;&lt;Button-1&gt;&#39; =&gt; [ \&amp;manipulate_link, $tag, &#39;sunken&#39; ] );            $t-&gt;tagBind( $tag,                &#39;&lt;ButtonRelease-1&gt;&#39; =&gt;                  [ \&amp;manipulate_link, $tag, &#39;raised&#39;, undef, \&amp;printme ] );            $tag++;        }        else {            $t-&gt;insert( &#39;end&#39;, $_ , &#39;tag1&#39; );        }    }    $t-&gt;insert( &#39;end&#39;, &quot;\n&quot; ); }}##############################################sub get_links{  my $url_in = shift;   # Set up a callback that collect image links  @links = ();  # a global# Make the parser.  Unfortunately, we don&#39;t know the base yet# (it might be diffent from $url)my $p = HTML::LinkExtor-&gt;new(\&amp;callback,\@links);# Request document and parse it as it arrivesmy $res =  $ua-&gt;request( HTTP::Request-&gt;new( GET =&gt; $url_in ),                             sub { $p-&gt;parse( $_[0] );     } );# Expand all  URLs to absolute onesmy $base = $res-&gt;base;@links = map { $_ = url( $_, $base )-&gt;abs; } @links;return @links;}#################################################sub callback {       my ( $tag, %attr) = @_;    return if $tag ne &#39;a&#39;;     # we only look closer at &lt;a href ...&gt;    push( @links, values %attr );}####################################################sub printme {#    print &quot;@_\n&quot;;    $_[0]-&gt;tagConfigure( $_[2], -foreground =&gt; &#39;yellow&#39;, -background =&gt; &#39;black&#39; );    push @selected_cats, $_[1];    #now we have an array of urls to fetch and process for all    #video links    #this is done in the &#39;Done Selecting&#39; callback}#######################################################sub manipulate_link {    # manipulate the link as you press the mouse key    my ($a)      = shift;    my ($tag)    = shift;    my ($relief) = shift;    my ($cursor) = shift;    my ($after)  = shift;    # by configuring the relief (to simulate a button press)    $a-&gt;tagConfigure( $tag, -relief =&gt; $relief, -borderwidth =&gt; 1 );    # by changing the cursor between hand and xterm    $a-&gt;configure( -cursor =&gt; $cursor ) if ($cursor);    # and by scheduling the specified action to run &quot;soon&quot;    if ($after) {        my ($s) = $a-&gt;get( $a-&gt;tagRanges($tag) );        $mw-&gt;after( 100, [ $after, $a, $s, $tag, @_ ] ) if ($after);    }}########################################################sub get_file{  my @types =( [&quot;mpeg,mp3,avi&quot;, [qw/.mpg .mpeg .mp3 .avi .flv/]],);  my $file = $mw-&gt;getOpenFile( -filetypes =&gt; \@types );  return $file;}###########################################################sub set_sound{   &amp;stop;  if($sound == 1 ){ @options = grep{ $_ ne &#39;-nosound&#39;} @options;}  else{ unshift @options, &#39;-nosound&#39;;}  &amp;start_player;   &amp;play($cur_play);}##############################################################sub start_player{  $pid = open(MP, &quot;| mplayer @options  init.mpg &gt;/dev/null 2&gt;&amp;1 &quot;);   $canv-&gt;itemconfigure($dcontitem,-state =&gt; &#39;normal&#39;);}##############################################################sub play {      my $mpg = shift || &#39;init.mpg&#39;;             syswrite(MP, &quot;loadfile $mpg\n&quot;);      $cur_play = $mpg;      my $filename = substr ($mpg, rindex ($mpg, &quot;/&quot;) + 1);      $mw-&gt;configure(-title=&gt;$filename);      $title = $filename; }###################################################################sub stop{       syswrite(MP, &quot;quit\n&quot;);       $canv-&gt;itemconfigure($dcontitem,-state =&gt; &#39;hidden&#39;);       killfam 9, $pid;       close MP;}#################################################################sub close_it_up{&amp;stop;$thread_die = 1;$thread-&gt;join;exit;}##############################################################################sub start_downloads{      foreach my $page( @selected_cats ){         my @links1 = &amp;get_links( $page );         # &quot;http://youtube.com/watch?v=EkTpUxh8Vxc&quot;;         my $lead = &#39;http://youtube.com/watch?v=&#39;;         my $rx = qr/\Q$lead\E(.*)/;     @links1 = grep{/$rx/} @links1; #remove dups         @links1 = keys %{{map{$_,1} @links1}};         #print &quot;@links1\n&quot;; foreach(@links1){ push @selected , $_  }      }          #print join &quot;\n&quot;, @selected,&quot;\n&quot;;          #start downloading thread if needed  if( scalar @selected &gt; 0 ){     $thread_go = 1;         # timer to autoplay first download    $timer = $mw-&gt;repeat(500, sub{           if( scalar @ready &gt; 0 ){                if( ! $playing ){ &amp;play( $ready[0] ) };             $timer-&gt;cancel;     }            });      #update download list (hack for tk thread safety)    #use 10 seconds to allow time to make selections    #definitely a hack :-)    $timer1 =       $mw-&gt;repeat(10000, sub{              @ready_lb = @ready;      $lb-&gt;update;      });   }}#############################################################sub work{  no warnings &quot;all&quot;; #stops a harmless shared var warning    my $received_size;  my $request_time;  my $last_update;  my $ua = LWP::UserAgent-&gt;new();$|++; while(1){   if($thread_die == 1){ goto END };           if ( $thread_go  == 1 ){      print &quot;starting next page retrieval\n&quot;;      my $urlin  = shift @selected;      my $content = get( $urlin  ) or die &quot;$!\n&quot;;       print &quot;done page retrieval\n&quot;;            #get human friendly title for video      $content =~ /&lt;title&gt;(.*)&lt;\/title&gt;/;      my $title = $1;        #put underscores for spaces in title      $title =~ tr/ /_/;       # regex for 2 key text strings which identify the video file     # the second one $2 is unique for each download attempt     $content =~ /player2\.swf\?video_id=([^&amp;]+)&amp;.*t=([^&amp;]+)&amp;/ ;      print $1, &quot;\n&quot; , $2, &quot;\n&quot;;            #make add title to filename for ease of identification     my $infile = $title.&#39;--&#39;.$1.&#39;.flv&#39;;  #add a .flv extension     #http://www.youtube.com/get_video?video_id=p_YMigZmUuk&amp;t=OEgsToPDskLRl9-iKyfQVcNT8xes2OIT     my $get_url = &#39;http://www.youtube.com/get_video?video_id=&#39;.$1.&#39;&amp;t=&#39;.$2;     print &quot;gettin video file $get_url\n&quot;;     # don&#39;t buffer the prints to make the status update     $| = 1;     open(IN,&quot;&gt; $infile&quot;) or die &quot;$_\n&quot;;      $received_size = 0;     my $url = $get_url;     print &quot;Fetching $url\n&quot;;     $request_time = time;     $last_update = 0;     my $response = $ua-&gt;get($url,                        &#39;:content_cb&#39;     =&gt; \&amp;callback_t,                        &#39;:read_size_hint&#39; =&gt; 8192,                       );     print &quot;\n&quot;;     close IN;     print &quot;$infile done\n&quot;;       push @ready, $infile;       }else         { select(undef,undef,undef,.1); } #sleep .1 second  } #end while loop sub callback_t {   my ($data, $response, $protocol) = @_;   my $total_size = $response-&gt;header(&#39;Content-Length&#39;) || 0;   $received_size += length $data;   # write the $data to a filehandle or whatever should happen   # with it here.   print IN $data;   my $time_now = time;   if($thread_go == 0){last}   if($thread_die == 1){ goto END };    # this to make the status only update once per second.   return unless $time_now &gt; $last_update or $received_size == $total_size;   $last_update = $time_now;   print &quot;\rReceived $received_size bytes&quot;;   printf &quot; (%i%%)&quot;, (100/$total_size)*$received_size if $total_size;   printf &quot; %6.1f/bps&quot;, $received_size/(($time_now-$request_time)||1)      if $received_size; }END:}###################################################################sub make_init{use MIME::Base64;                                                                         my $init_mpg =&#39; UklGRvYUAABBVkkgTElTVOgRAABoZHJsYXZpaDgAAABAQg8AfJIAAAAAAAAQCQAAAwAAAAAAAAABAAAAAAAQAMAAAACQAAAAAAAAAAAAAAAAAAAAAAAAAExJU1SQEAAAc3RybHN0cmg4AAAAdmlkc0RJVlgAAAAAAAAAAAAAAAABAAAAAQAAAAAAAAADAAAAAAAQAP////8ARAEAAAAAAMAAkABzdHJmKAAAACgAAADAAAAAkAAAAAEAGABESVZYAEQBAAAAAAAAAAAAAAAAAAAAAABKVU5LFBAAAAQAAAAAAAAAMDBkYwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEpVTksEAQAAb2RtbGRtbGj4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABMSVNUwgIAAG1vdmkwMGRjbAEAAAAAAbABAAABtYkTAAABAAAAASAAxI2IAA0GBBIUYwAAAbJGRm1wZWcwLjQuOGI0NjgwAH8AAAGzABAHAAABthYPGC/bfxtt/G238bbfxtt/G238bbfxtt/G238bbfxtt/G238bbfxtt/G238bbfxtt/G238bbfxtt/G238bbfxtt/G238bbfxtt/G238bbfxtt/G238bbfxtt/G238bbfxtt/G238bbfxtt/G238bbfxtt/G238bbfxtt/G238bbfxtt/G238bbfxtt/G238bbfxtt/G238bbfxtt/G238bbfxtt/G238bbfxtt/G238bbfxtt/G238bbfxtt/G238bbfxtt/G238bbfxtt/G238bbfxtt/G238bbfxtt/G238bbfxtt/G238bbfxtt/G238bbfxtt/G238bbfxtt/G238bbfxtt/G238bbfxtt/G238bbfxtt/G238bbfxtt/G238bbfxtt/G2378wMGRjIwEAAAAAAbZrgRC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OC+5wX3OfwAwMGRjFQAAAAAAAbZrAR//////////////////fwBpZHgxMAAAADAwZGMQAAAABAAAAGwBAAAwMGRjAAAAAHgBAAAjAQAAMDBkYwAAAACkAgAAFQAAAA==&#39;;open(FH,&quot;&gt; init.mpg&quot;) or die &quot;$!\n&quot;;print FH decode_base64($init_mpg);close FH;}&lt;/pre&gt;
    </description>
</item>

        

<item>
    <title>Guess Number (alandev)</title>
    <link>http://prlmnks.org/html/570811.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/570811.html</guid>

    <description>
        i  wrote code that would have a number and the user got to guess it correctly. every time user guess is wrong the number gets updated/changed. &lt;pre class=&quot;block_code&quot;&gt;#!/usr/bin/perluse term;$SIG{INT}=&#39;IGNORE&#39;;$seed=substr(rand(1)*10,0,1);$seed+=1;print &quot;Guess the Code:&quot;;$st=time();$ip=&lt;&gt;;chop($ip);while($seed != $ip){$seed=substr(rand(1)*10,0,1);$seed++;$ip=&lt;&gt;;}if($seed == $ip){        $et=time();        $tt=$et-$st;print &quot;\n  Time Taken 2 break the Code ..:&quot;,$tt,&quot; Seconds\n&quot;;}&lt;/pre&gt;
    </description>
</item>

        

<item>
    <title>Another date parsing technique (Boyd)</title>
    <link>http://prlmnks.org/html/570794.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/570794.html</guid>

    <description>
        Probably not new, but it is to me - a quick way to create a date string w/o using modules, etc.&lt;pre class=&quot;block_code&quot;&gt;my $date_str =   sprintf q{%02d%s%d},   (split /\s+/,localtime)[2,1,4];&lt;/pre&gt;
    </description>
</item>

        

<item>
    <title>YouTube Video Downloader (zentara)</title>
    <link>http://prlmnks.org/html/570467.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/570467.html</guid>

    <description>
        Shamelessly converted to perl from the python script &lt;a href=http://www.arrakis.es/~rggi3/youtube-dl/&gt; youtube.dl &lt;/a&gt;&lt;p&gt;It downloads the front page, extracts the necessary strings, then gets the flash video file ( .flv ) which is then opened in mplayer. The large video download has a progress callback.&lt;pre class=&quot;block_code&quot;&gt;#!/usr/bin/perluse warnings;use LWP::Simple;use LWP::UserAgent;# shamelessly reversed engineered from a python script :-) print &quot;startring first page retrieval\n&quot;;my $urlin  = shift || &quot;http://youtube.com/watch?v=EkTpUxh8Vxc&quot;;my $content = get( $urlin  ) or die &quot;$!\n&quot;; print &quot;done first page retrieval\n&quot;;#print $content;# regex for 2 key text strings which identify the video file# the second one $2 is unique for each download attempt$content =~ /player2\.swf\?video_id=([^&amp;]+)&amp;.*t=([^&amp;]+)&amp;/ ;print $1, &quot;\n&quot; , $2, &quot;\n&quot;;  my $infile = $1.&#39;.flv&#39;;  #add a .flv extension#http://www.youtube.com/get_video?video_id=p_YMigZmUuk&amp;t=OEgsToPDskLRl9-iKyfQVcNT8xes2OITmy $get_url = &#39;http://www.youtube.com/get_video?video_id=&#39;.$1.&#39;&amp;t=&#39;.$2;print &quot;gettin video file $get_url\n&quot;;# don&#39;t buffer the prints to make the status update$| = 1;open(IN,&quot;&gt; $infile&quot;) or die &quot;$_\n&quot;; my $ua = LWP::UserAgent-&gt;new();my $received_size = 0;my $url = $get_url;print &quot;Fetching $url\n&quot;;my $request_time = time;my $last_update = 0;my $response = $ua-&gt;get($url,                        &#39;:content_cb&#39;     =&gt; \&amp;callback,                        &#39;:read_size_hint&#39; =&gt; 8192,                       );print &quot;\n&quot;;close IN;#play the flv file with mplayersystem( &quot;mplayer $infile&quot; );#############################################sub callback {  my ($data, $response, $protocol) = @_;  my $total_size = $response-&gt;header(&#39;Content-Length&#39;) || 0;  $received_size += length $data;  # write the $data to a filehandle or whatever should happen  # with it here.  print IN $data;  my $time_now = time;  # this to make the status only update once per second.  return unless $time_now &gt; $last_update or $received_size == $total_size;  $last_update = $time_now;  print &quot;\rReceived $received_size bytes&quot;;  printf &quot; (%i%%)&quot;, (100/$total_size)*$received_size if $total_size;  printf &quot; %6.1f/bps&quot;, $received_size/(($time_now-$request_time)||1)     if $received_size;}__END__&lt;/pre&gt;
    </description>
</item>

        

<item>
    <title>Recursively display nested lists with Template Toolkit (friedo)</title>
    <link>http://prlmnks.org/html/570059.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/570059.html</guid>

    <description>
        Template Toolkit does not allow recursively including template files, but you can use a VIEW to recurse over a data structure. VIEWs are still experimental but it works for me.&lt;pre class=&quot;block_code&quot;&gt;use Template;use strict;use warnings;my $t = Template-&gt;new;my @nodes = ({name =&gt; &quot;one&quot;},{name =&gt; &quot;two&quot;, children =&gt; [ {name =&gt; &quot;red&quot;},                              {name =&gt; &quot;green&quot;} ] },{name =&gt; &quot;three&quot;, children =&gt; [  {name =&gt; &quot;blah&quot;, children =&gt; [    {name =&gt; &quot;yakko&quot; },    {name =&gt; &quot;wacko&quot; },    {name =&gt; &quot;dot&quot; }   ]  }]} );$t-&gt;process(&quot;rec.tt&quot;, { nodes =&gt; \@nodes } );&lt;/pre&gt;&lt;p&gt;And the template:&lt;p&gt;&lt;pre class=&quot;block_code&quot;&gt;[% VIEW nested_list %]  [% BLOCK list %]    &lt;ul&gt;      [% FOREACH i IN item %]        &lt;li&gt;[% i.name %]&lt;/li&gt;        [% IF i.children %]          [% view.print(i.children.list) %]        [% END %]      [% END %]    &lt;/ul&gt;  [% END %][% END %][% nested_list.print(nodes) %]&lt;/pre&gt;&lt;p&gt;And that outputs:&lt;p&gt;    &lt;ul&gt;              &lt;li&gt;one&lt;/li&gt;                       &lt;li&gt;two&lt;/li&gt;                       &lt;ul&gt;              &lt;li&gt;red&lt;/li&gt;                       &lt;li&gt;green&lt;/li&gt;                   &lt;/ul&gt;                        &lt;li&gt;three&lt;/li&gt;                       &lt;ul&gt;              &lt;li&gt;blah&lt;/li&gt;                       &lt;ul&gt;              &lt;li&gt;yakko&lt;/li&gt;                       &lt;li&gt;wacko&lt;/li&gt;                       &lt;li&gt;dot&lt;/li&gt;                   &lt;/ul&gt;                    &lt;/ul&gt;                    &lt;/ul&gt;
    </description>
</item>

        

<item>
    <title>A little demo for Net::SSH2 (zentara)</title>
    <link>http://prlmnks.org/html/569657.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/569657.html</guid>

    <description>
        From the Net::SSH2 README&lt;p&gt;Net::SSH2 is a perl interface to the libssh2 (http://www.libssh2.org)library.  It supports the SSH2 protocol (there is no support for SSH1)with all of the key exchanges, ciphers, and compression of libssh2.At present, libssh2 requires OpenSSL (http://www.openssl.org) and canoptionally use zlib for compression (http://www.zlib.net).The Net::SSH::Perl modules are showing signs of age; with the requirementto be compatible with SSH versions 1 and 2, support of newer features suchas channels is difficult; it also has many dependencies, some of whichare hard to build (e.g. Math::Pari).&lt;p&gt;So to help you get into it, here is a simple demo of what works, including a key authorization example. Some of the docs are hard to deal with because of way xs works, so here are some working usages that should allow you to handle almost anything, sftp, scp, running scripts, etc.&lt;pre class=&quot;block_code&quot;&gt;#!/usr/bin/perluse warnings;use strict;use Net::SSH2;use Data::Dumper;# assuming a user named &#39;z&#39; for demonstration # connecting to localhost, so you need your sshd running# see maillist archives at# http://lists.sourceforge.net/lists/listinfo/ssh-sftp-perl-users# for deeper discussionsmy $ssh2 = Net::SSH2-&gt;new();#connect$ssh2-&gt;connect(&#39;localhost&#39;) or die &quot;Unable to connect Host $@ \n&quot;;# authorize# this works but I use keys below # $ssh2-&gt;auth_password(&#39;z&#39;,&#39;foopass&#39;) or die &quot;Unable to login $@ \n&quot;;#this dosn&#39;t work#$ssh2-&gt;auth(username=&gt;&#39;z&#39;, interact =&gt; 1);# for a tutorial on auth-keys setup, see# http://cfm.gs.washington.edu/security/ssh/client-pkauth/#get the password for the keyuse Term::ReadKey;print &quot;And your key password: &quot;;ReadMode(&#39;noecho&#39;);chomp(my $pass = ReadLine(0));ReadMode(&#39;restore&#39;);print &quot;\n&quot;;$ssh2-&gt;auth_publickey(&#39;z&#39;,         &#39;/home/z/.ssh/id_rsa.pub&#39;, #testing on localhost &#39;/home/z/.ssh/id_rsa&#39;,      $pass );my $chan = $ssh2-&gt;channel();$chan-&gt;exec(&#39;ls -la&#39;);while (&lt;$chan&gt;){ print } #will get dir named 2my $chan1 = $ssh2-&gt;channel();$chan1-&gt;exec(&#39;ls -la 2&#39;);while (&lt;$chan1&gt;){ print } # mkdir with sftpmy $sftp = $ssh2-&gt;sftp();my $dir = &#39;/home/z/3&#39;;$sftp-&gt;mkdir($dir);my %stat = $sftp-&gt;stat($dir);print Dumper([\%stat]), &quot;\n&quot;;#put a filemy $remote = &quot;$dir/&quot;.time;$ssh2-&gt;scp_put($0, $remote);#get a small file to a scalaruse IO::Scalar;my $local = IO::Scalar-&gt;new; #it needs a blessed reference$ssh2-&gt;scp_get($remote, $local);print &quot;$local\n\n&quot;;#get a large file like a 100Meg wav file my $remote1 = $dir.&#39;/1.wav&#39;;use IO::File;my $local1 = IO::File-&gt;new(&quot;&gt; 2.wav&quot;); #it needs a blessed reference $ssh2-&gt;scp_get($remote1, $local1);# get a dirlistmy $dh = $sftp-&gt;opendir($dir);while(my $item = $dh-&gt;read) {    print $item-&gt;{&#39;name&#39;},&quot;\n&quot;;    }#shell usemy $chan2 = $ssh2-&gt;channel();$chan2-&gt;shell();print $chan2 &quot;uname -a\n&quot;;print &quot;LINE : $_&quot; while &lt;$chan2&gt;;print $chan2 &quot;who\n&quot;;print &quot;LINE : $_&quot; while &lt;$chan2&gt;;$chan2-&gt;close;__END__&lt;/pre&gt;
    </description>
</item>

        

<item>
    <title>Find the name of a CODEref (Dylan)</title>
    <link>http://prlmnks.org/html/569508.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/569508.html</guid>

    <description>
        Inspired by http://perlmonks.org/?node_id=448016, I wrote this little function to figure out the name of a CODEref.Uses a nifty B:: hack.&lt;pre class=&quot;block_code&quot;&gt;use B;sub findit {    my $ref = shift;    die &quot;I only work for CODErefs!&quot; unless ref $ref eq &#39;CODE&#39;;    my $package = B::svref_2object($ref)-&gt;START-&gt;stashpv;    local(*alias, *stash);    *stash = *{&quot;${package}::&quot;};    while ((my $varname, my $globvalue) = each %stash){        next if $varname eq &quot;alias&quot;;        *alias = $globvalue;        if (defined(&amp;alias)){               if ($ref == \&amp;alias){                return $varname;            }        }    }    return undef;}&lt;/pre&gt;
    </description>
</item>

        

<item>
    <title>Zero sound detection with Tk graphics (zentara)</title>
    <link>http://prlmnks.org/html/567312.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/567312.html</guid>

    <description>
        Someone asked on the perl.beginners list how to detect silence on the linux sound card, to be used in a studio to detect when the DJ is sleeping. :-)  This reads /dev/dsp and detects when sound is zero.  Just play a song on your alsa sound system (standard on linux), start this script, and watch. :-)  It works for wavs, mp3&#39;s, etc, but not midi&#39;s.&lt;p&gt;UPDATE Aug16,2006....fixed a division by zero error when app is started with a quiet sound card.&lt;pre class=&quot;block_code&quot;&gt;#!/usr/bin/perluse warnings;use strict;use Tk;use Audio::DSP;use constant PI =&gt; 3.1415926;#alsamixer must be setup right, AC&#39;97 capture adjusts sensitivity,#just turn it up to 100 for this to work as intendedmy ($buf, $chan, $fmt, $rate) = (4096, 1, 16 , 8000);my $dsp = new Audio::DSP(buffer   =&gt; $buf,                     channels =&gt; $chan,                     format   =&gt; $fmt,                     rate     =&gt; $rate);$dsp-&gt;init() || die $dsp-&gt;errstr();my $mw = MainWindow-&gt;new;my $x = 300;my $y = 300;$mw-&gt;protocol(&#39;WM_DELETE_WINDOW&#39; =&gt; sub { &amp;clean_exit });$mw-&gt;fontCreate(&#39;big&#39;, -family=&gt;&#39;arial&#39;,     -weight=&gt;&#39;bold&#39;, -size=&gt; 36 );my $count_tot = 0;my $count_max = 0;my $c = $mw-&gt;Canvas(              -width =&gt; $x,              -height =&gt; $y,              -bd =&gt; 2,              -relief =&gt; &#39;sunken&#39;,              -background =&gt; &#39;black&#39;,              )-&gt;pack();$c-&gt;createLine( $x/2, $y/2, 10 , $y/2 ,          -tags =&gt; [&#39;needle&#39;],          -arrow =&gt; &#39;last&#39;,          -width =&gt; 15,          -fill =&gt; &#39;hotpink&#39;,           );my $gauge = $c-&gt;createArc(        10,10, $x-10,$y-10,        -start =&gt; 0,        -style =&gt; &#39;arc&#39;,        -width =&gt; 5,        -extent =&gt; 180,        -outline =&gt; &#39;skyblue&#39;,        -tags =&gt; [&#39;gauge&#39;],);my $hub = $c-&gt;createArc(        ($x/2 - 20), ($y/2 - 20) ,( $x/2 + 20) ,( $y/2 + 20),        -start =&gt; 90,        -extent =&gt; 359,        -fill =&gt; &#39;lightgreen&#39;,        -tags =&gt; [&#39;hub&#39;],);my $text = $c-&gt;createText(      $x/2, $y/2 + 150,       -text  =&gt; $count_max,       -font  =&gt; &#39;big&#39;,       -fill  =&gt; &#39;yellow&#39;,       -anchor =&gt; &#39;s&#39;,       -tags =&gt; [&#39;text&#39;] );$c-&gt;raise(&#39;needle&#39;,&#39;text&#39;);$c-&gt;raise(&#39;hub&#39;,&#39;needle&#39;);$mw-&gt;bind(&#39;&lt;space&gt;&#39;,sub{ &amp;toggle_status  });$mw-&gt;waitVisibility;my $timer = $mw-&gt;repeat(50,sub{                     my $value = &amp;update_meter;                    $value = sprintf(&#39;%2.1f&#39;,$value);    if($value &lt;= 0){$value = 0 }                    if($value &gt;= 100){$value = 100}                  my $pos = $value/100;                    my $x1 = $x/2 - .95*$x/2 * (cos( $pos * PI ));                  my $y1 = $y/2 - .95*$y/2 * (sin( $pos * PI ));                  $c-&gt;coords(&#39;needle&#39;, ($x/2), ($y/2), $x1, $y1);                   if($value &gt; $count_max){ $count_max = $value }                   if($value == 0){ $count_max = 0 }                    $c-&gt;itemconfigure($text, -text =&gt; $value);                    $mw-&gt;update;                });MainLoop;#########################################################sub update_meter {  my $samples = 15;  my $num_tot = 0;  my $div_tot = 0;  my $value =0;# Record x samples of soundfor (1..$samples) {        #read 16 bits of raw data        my $data = $dsp-&gt;dread(16); # || die $dsp-&gt;errstr();        my $num =  unpack( &#39;v&#39;, $data  );            #filter out baseline noise    if($num &gt; 65000){next}else{    #print  &quot;$num &quot;;            $num_tot += $num;            $div_tot += 32768;  #gives a good average} } if( $div_tot != 0 ){   $value = ($num_tot/$div_tot) * 100;} return $value;}####################################################################### sub clean_exit{    $timer-&gt;cancel;    $dsp-&gt;close();    exit;}#################################################################__END__&lt;/pre&gt;
    </description>
</item>

        

<item>
    <title>Finding all files that are writeable by the current user (imp)</title>
    <link>http://prlmnks.org/html/567252.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/567252.html</guid>

    <description>
        One liner that identifies all files on the current system that are writeable by the current user.This version will find the files/directories writeable by the current user:&lt;pre class=&quot;block_code&quot;&gt;perl -MFile::Find -e &#39;find(sub {my $f = $File::Find::name; print $f, &quot;\n&quot; if -w $f &amp;&amp; !-l $f}, &quot;/&quot;)&#39;&lt;/pre&gt;The following snippet will identify the files that are writeable for the given user - but only if the current user can access all of the directories that the specified user can see. If you can&#39;t see it, you can&#39;t check it. Note that this version will collect all of the files before printing anything.&lt;pre class=&quot;block_code&quot;&gt;use File::Find::Rule::Permissions;my $user = @ARGV ? $ARGV[0] : $ENV{USER};print $_,&quot;\n&quot; for File::Find::Rule::Permissions-&gt;file() -&gt;permissions( user =&gt; $user, isWriteable =&gt; 1) -&gt;in(&quot;/&quot;);&lt;/pre&gt;
    </description>
</item>

        

<item>
    <title>dump-static-nodes.pl - Pull content from your webserver according to .htaccess (Corion)</title>
    <link>http://prlmnks.org/html/567111.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/567111.html</guid>

    <description>
        &lt;p&gt;To create static versions of pages that get hit from the outside, I wrote this program, which runs as a cron job. It parses the &lt;tt class=&quot;inline_code&quot;&gt;.htaccess&lt;/tt&gt; file of the webserver and createsstatic HTML versions of the pages listed in the &lt;tt class=&quot;inline_code&quot;&gt;.htaccess&lt;/tt&gt; file. Currently, thereis no parsing so that the redirect from the &lt;tt class=&quot;inline_code&quot;&gt;.htaccess&lt;/tt&gt; gets generated as the output file, but as entries into the &lt;tt class=&quot;inline_code&quot;&gt;.htaccess&lt;/tt&gt; file get made by another script, that&#39;s not as problematic.&lt;/p&gt;&lt;pre class=&quot;block_code&quot;&gt;#!/usr/bin/perl -wuse strict;use File::Basename;use LWP::Simple;use Getopt::Long;GetOptions(   &#39;wwwroot:s&#39;   =&gt; (\my $wwwroot),   &#39;staticdir:s&#39; =&gt; (\my $outdir),   &#39;server:s&#39;    =&gt; (\my $server),   &#39;node:i&#39;      =&gt; (\my @nodes),   &#39;htaccess:s&#39;  =&gt; (\my $htaccess),   &#39;savepath:s&#39;  =&gt; (\my $savepath),);$wwwroot  ||= &#39;./public_html&#39;;#$htaccess ||= &quot;$wwwroot/.htaccess&quot;;$server   ||= &quot;perlmonks.org&quot;;$savepath ||= $wwwroot;my $uri = &quot;http://$server?node_id=%d;style=static&quot;;my $save = &quot;$savepath/%d.html&quot;;# -d $wwwroot or die &quot;wwwroot: &#39;$wwwroot&#39; is no directory.&quot;;-d $savepath or die &quot;savepath: &#39;$savepath&#39; is no directory.&quot;;if (! scalar @nodes) {    open my $hta, &quot;&lt;&quot;, $htaccess        or die &quot;Couldn&#39;t read &#39;$htaccess&#39; : $!&quot;;    push @nodes, map { /^\s*RewriteCond %\{QUERY_STRING\} node_id=(\d+)\$/ ? $1 : () } &lt;$hta&gt;;};for my $node (@nodes) {    my $url = sprintf $uri, $node;    my $target = sprintf $save, $node;    print &quot;Saving $node via $url to $target&quot;;    printf &quot;, %d\n&quot;, mirror($url, $target);};&lt;/pre&gt;
    </description>
</item>

        

<item>
    <title>Autovivification trick (blazar)</title>
    <link>http://prlmnks.org/html/567020.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/567020.html</guid>

    <description>
        Minimal example exhibiting a &lt;strong&gt;double reference autovivification trick&lt;/strong&gt; (learnt from &lt;em&gt;Brian McCauley&lt;/em&gt; in a &lt;a href=&quot;/out/href/news:comp.lang.perl.misc&quot;&gt;clpmisc&lt;/a&gt; &lt;a href=&quot;/out/href/news:1155102735.358626.78050@i3g2000cwc.googlegroups.com&quot;&gt;thread&lt;/a&gt;) to convert a list of structured strings as that below the &lt;tt class=&quot;inline_code&quot;&gt;__END__&lt;/tt&gt; token to a complex data structure as that illustrated by the output of the program. [id://567024|More details] follow.&lt;pre class=&quot;block_code&quot;&gt;#!/usr/bin/perluse strict;use warnings;use Data::Dumper;my %dirhash;while (&lt;DATA&gt;) {    chomp;    my $last=\\%dirhash;    $last=\$$last-&gt;{$_} for split qr|/|;}print Dumper \%dirhash;__END__/file.txt/a/file.txt/a/b/c/a/b/c/file.txt/z/m/w/file.txt&lt;/pre&gt;
    </description>
</item>

        

<item>
    <title>Remove broken symlinks with IO::All (Dylan)</title>
    <link>http://prlmnks.org/html/566997.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/566997.html</guid>

    <description>
        &lt;p&gt;This is a short script using IO::All to remove broken symlinks.&lt;p&gt;Note, it has to redefine the readlink() method, because as of version 0.35 of IO::All, readlink doesn&#39;t handle relative symlinks.&lt;p&gt;IO::All sure makes my life easier!&lt;pre class=&quot;block_code&quot;&gt;#!/usr/bin/perluse strict;use warnings;use IO::All::Link; # Because we redefine readlink()...use IO::All;my $file = shift @ARGV || &#39;.&#39;;my @ios = ( io($file) );while (my $io = shift @ios) {    if ($io-&gt;is_dir) {        push @ios, $io-&gt;all;    } elsif ($io-&gt;is_link and not $io-&gt;readlink-&gt;exists) {        print &quot;$io is broken, removing.\n&quot;;        $io-&gt;unlink;    }}# this has been submitted as a patch to IO::All...no warnings &#39;redefine&#39;;sub IO::All::Link::readlink {    my $io = shift;    my $path = CORE::readlink($io-&gt;name);    unless (File::Spec-&gt;file_name_is_absolute($path)) {        $path = File::Spec-&gt;join($io-&gt;filepath, $path);    }    IO::All-&gt;new($path);}&lt;/pre&gt;
    </description>
</item>

        

<item>
    <title>pickFromRange (tye)</title>
    <link>http://prlmnks.org/html/566425.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/566425.html</guid>

    <description>
        &lt;p&gt;This uses a partial Fisher-Yates shuffle to efficiently pick a random selection of elements from a contiguous range of integers, using a hash to prevent using a lot of memory when the range of integers to choose from is huge.&lt;/p&gt;&lt;p&gt;If the number of integers you want to select is nearly as large as the range you are selecting from, then using a hash in this way isn&#39;t a big win and you are probably better off just putting the range of integers into an array and doing a partial Fisher-Yates shuffle on it.&lt;/p&gt;&lt;p&gt;If you can rely on your version(s) of Perl having the // operator, then the code can be simplified, replacing all but the first and last two lines of the loop with the two commented-out lines.&lt;/p&gt;&lt;p&gt;Command-line usage of included sample code:&lt;/p&gt;&lt;pre class=&quot;block_code&quot;&gt;    perl pickFromRange.pl [ count [ max | min max ] ]    pickFromRange [ count [ max | min max ] ]&lt;/pre&gt;&lt;p&gt;Count defaults to 20.  If max is not given, then the range 100..999 is used.  If max is given but not min, then 1..max is used.&lt;/p&gt;&lt;p&gt;(Minor updates applied.)&lt;/p&gt;&lt;pre class=&quot;block_code&quot;&gt;#!/usr/bin/perl -wuse strict;sub pickFromRange{    my( $count, $min, $max )= @_;    my $range= $max - $min + 1;    die &quot;pickFromRange: $max - $min + 1 &lt; $count&quot;   if  $range &lt; $count;    my @pick;    my %replace;    while(  0 &lt; $count--  ) {        my $pick= $min + int( rand($range) );        my $next= $replace{$pick};        push @pick, defined($next) ? $next : $pick;        # push @pick, $replace{$pick} // $pick;        $next = $replace{$max};        $replace{$pick}= defined($next) ? $next : $max;        # $replace{$pick}= $replace{$max} // $max;        delete $replace{$max--};        $range--;    }    return @pick;}my $count=  @ARGV ? shift(@ARGV) : 20;my( $min, $max )= !@ARGV ? (100,999) : 1==@ARGV ? (1,@ARGV) : @ARGV;my @pick= pickFromRange( $count, $min, $max );print &quot;@pick\n&quot;;&lt;/pre&gt;
    </description>
</item>

        

<item>
    <title>Perl template maker (fatalserpent)</title>
    <link>http://prlmnks.org/html/562953.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/562953.html</guid>

    <description>
        This script takes one argument and outputs a perl executable file ready to have code added to it! w/e lolz. It&#39;s easy enought to figure out anyway... &lt;i&gt;PD code&lt;/i&gt;&lt;pre class=&quot;block_code&quot;&gt;#!/usr/bin/perl$filename = @ARGV[0];open(FILE, &quot;&gt;$filename&quot;);print{FILE}&quot;#!/usr/bin/perl\n# $filename\nuse warnings\;\nuse strict\;\n&quot;;close(FILE);system(&quot;chmod 755 $filename&quot;);&lt;/pre&gt;
    </description>
</item>

        

<item>
    <title>xd and dx -- hexdump for debugging purposes (Skeeve)</title>
    <link>http://prlmnks.org/html/562799.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/562799.html</guid>

    <description>
        I often need hexdumps of files or output streams. So I wrote these 2 little helpers years ago. Maybe others find them useful too (and because [neversaint] asked me in th CB to post them...)&lt;pre class=&quot;block_code&quot;&gt;###### xd -- hexdump#!/usr/bin/perl@fill= qw( .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. );if (scalar(@ARGV)) {foreach $file(@ARGV) {$size= -s $file;$form= length(sprintf(&quot;%x&quot;,$size))-1;++$form unless $form;print &quot;File: &quot;,$file,&quot;\n&quot;;open (IN,$file);&amp;dump(*IN, $form);close (IN)}}else {&amp;dump(*STDIN, 4);}sub dump {local(*IN, $form)= @_;my ($buf, $i);while ($rb= read(IN, $buf, 16)) {@x= unpack(&quot;H2&quot; x $rb, $buf);$buf=~ s/[\x00-\x1f\x7f-\xff]/./g;$buf.= &#39; &#39; x (16-length($buf));printf (&quot;%0${form}x0: %s [%s]\n&quot;,$i++,,sprintf (&quot;%s %s %s %s  %s %s %s %s - %s %s %s %s  %s %s %s %s&quot;, @x, @fill),$buf);}}###### dx -- undump the dump#!/usr/bin/perlif (scalar(@ARGV)) {foreach $file(@ARGV) {open (IN,$file);&amp;undump(*IN);close (IN)}}else {&amp;undump(*STDIN);}sub undump {local(*IN)= @_;local($_);while (&lt;IN&gt;) {#next unless s/^([0-9a-f]+)://;s/^([0-9a-f]+)://i;s/[^\-\s0-9a-f].*$//i;@match= /(\b[0-9a-f][0-9a-f]\b)/ig;print pack(&quot;H2&quot; x scalar(@match), @match);}}&lt;/pre&gt;
    </description>
</item>

        

<item>
    <title>King (alandev)</title>
    <link>http://prlmnks.org/html/562606.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/562606.html</guid>

    <description>
        &lt;pre class=&quot;block_code&quot;&gt;print &#39;===KING===&#39;&lt;/pre&gt;&lt;p&gt;&lt;small&gt;  Considered by [marto]: Restore content or Reap empty node. &lt;br /&gt;  Unconsidered by [planetscape]: keep (and edit) votes [id://409197|prevented] reaping ( keep:1 edit:12 reap:20 )&lt;/small&gt;&lt;/p&gt;
    </description>
</item>

        

<item>
    <title>tf - tail a file and output separator line when inactive (imp)</title>
    <link>http://prlmnks.org/html/562051.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/562051.html</guid>

    <description>
        I got tired of tailing an error log and hitting enter several times to create a gap between requests, so I automated this behaviour.This script will tail a file and print a line &#39;=&#39;x80 whenever there is a 2 second silent period - but will not output multiple separator lines for long silent periods.&lt;pre class=&quot;block_code&quot;&gt;#!/usr/bin/perluse strict;use warnings;# Pipe the output of tail -fopen TAIL, &quot;tail -f @ARGV |&quot; or die &quot;Failed to pipe to &#39;tail -f @ARGV&#39;. $!&quot;;# Create a handle for SIGALRM that outputs a line of &#39;=&#39;, 80 width.$SIG{ALRM}=sub{    printf &quot;\n%s\n&quot;, &#39;=&#39;x80;};# Read from TAIL# Print output# Set the alarm timer to 2 seconds.## By setting the alarm to 2 seconds with each line processed we can detect# the first 2 second silent period, and trigger $SIG{ALRM}.# After the alarm is triggered no further separators will be output until the## This will not trigger multiple separator lines, since alarm will not be reset# to 2 seconds until the next line is read.#print &amp;&amp; alarm(2) while&lt;TAIL&gt;__END__=head1 NAMEtf - script for tailing a file and outputting a separator line when inactive=head1 SYNOPSIS tf /var/log/messages=cut&lt;/pre&gt;
    </description>
</item>

        

<item>
    <title>More clear dumper debugging lines (jimt)</title>
    <link>http://prlmnks.org/html/560788.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/560788.html</guid>

    <description>
        &lt;p&gt;This is a trivially simple little formatting trick I use when tossing in lines to dump out during debugging or whatnot.&lt;/p&gt;&lt;p&gt;My thought process tends to go along the lines of, &quot;Hey, I need to check the values of this variable here, so I&#39;ll add a print statement...wait, I should print out another one. Wait, I really need to print out this whole complex data structure, I need to dump it.&quot;&lt;/p&gt;&lt;p&gt;Nothing special there, just use Data::Dumper and print it out. But I find that marginally annoying since (1) if I later want to shut off that print line and remove the module, I need to add two comments or (2) if I want to delete the statement, I need to remember to delete two lines, lest I end up with useless imports of Data::Dumper.&lt;/p&gt;&lt;p&gt;Solution? Simply toss the use onto the end of your debugging line. Since the use is hit at compile time, you&#39;re still importing the module in advance, so it works. Your print line is very clear on the left side of your code (no use in front of it), and then you only have one line to go back and clean up when you get rid of it.&lt;/p&gt;&lt;pre class=&quot;block_code&quot;&gt;print Dumper($some_complex_structure); use Data::Dumper;&lt;/pre&gt;
    </description>
</item>

        

<item>
    <title>Text aligner (in table) (Yunus)</title>
    <link>http://prlmnks.org/html/560581.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/560581.html</guid>

    <description>
        A set of routines to align text within columns. Suitable to build ascii-text based table. (include demo rountine)&lt;br&gt;&lt;br&gt;I dunno how to make CPAN modules (with POD). sorry. welcome any input/comment/feedback etc. Hopefully someone might find it useful ;)&lt;br&gt;&lt;br&gt;&lt;b&gt;update : &lt;/b&gt;Data (especially text) will be aligned (smartly) in column. &lt;pre class=&quot;block_code&quot;&gt;## By Mohd Yunus Sharum (youknows@gmail.com)# Universiti Putra Malaysia, Malaysia.## Copyright (C) 2006 Mohd Yunus Sharum## This program is free software; you can redistribute it and/or modify it under# the terms of the GNU General Public License as published by the Free Software# Foundation; either version 2  of the  License, or  (at your option) any later# version.## This program is distributed in the  hope that it will  be useful, but WITHOUT# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS# FOR A PARTICULAR PURPOSE.See the GNU General Public License for more details.## http://www.gnu.org/licenses/gpl.html#SEC1#use strict;# justification codes - used by alignColumns()#--------------use constant ALIGN_LEFT   =&gt; -1;use constant ALIGN_CENTER =&gt; 0;use constant ALIGN_RIGHT  =&gt; 1;# word separator  - used by alignColumns()#--------------my $separator = &#39;\s,.\-\+&#39;;my $not_separator = &#39;^&#39;.$separator;# functions&#39; declaration#--------------sub alignColumns($$$@);         # align data in multi columns (basic function)sub alignRows($$$@);            # same, but extended for multiple rows, no numbering featuressub numberedAlignRows($$$@);    # same, but extended with numbered rows#--------------# FUNCTION: #     SAMPLE PROGRAM - demonstrate the capability of aligner functions## IN: #     none# OUT:#     none#--------------sub main{    print &quot;Not auto numbered\n&quot;;    alignRows(&quot;&quot;,                         # output handle (default STDOUT)          [ALIGN_LEFT, ALIGN_LEFT],       # column alignment          [5, 50],                        # list of columns width          [&quot;Id&quot;, &quot;Residue&quot;],              # list of data          [&quot;-----&quot;, &quot;----------&quot;],          [&quot;123.12&quot;, &quot;AAABACACCA &quot;.                  &quot;AAABACACCACAGGATCCACACTCAAGTTT &quot;.                  &quot;AAABACACCACAGGATCCACACTCAAGTTTGGTAGGATCCACACTTTAAAGGATCCACACTAGGATCCACACTGGATCCACACT&quot;  ],          [&quot;A342&quot;, &quot;AGGATCCACAGGA&quot;],          [&quot;B652&quot;, &quot;AGGATCCACACTAGGATCCACACTAGGATCCACACT&quot; ]);    print &quot;\n\n&quot;;    print &quot;auto Numbered\n&quot;;    numberedAlignRows(&quot;&quot;,                 # output handle (default STDOUT)          [ALIGN_LEFT, ALIGN_LEFT],       # column alignment          [5, 50],                        # list of columns width          [&quot;Id&quot;, &quot;Residue&quot;],              # list of data          [&quot;-----&quot;, &quot;----------&quot;],          [&quot;123.12&quot;, &quot;AAABACACCACAGGATCCACACTCAAGTTTGGTAGGATCCACACTTTAAAGGATCCACACTAGGATCCACACTGGATCCACACT&quot;.                  &quot;AAABACACCACAGGATCCACACTCAAGTTTGGTAGGATCCACACTTTAAAGGATCCACACTAGGATCCACACTGGATCCACACT&quot;.                  &quot;AAABACACCACAGGATCCACACTCAAGTTTGGTAGGATCCACACTTTAAAGGATCCACACTAGGATCCACACTGGATCCACACT&quot;  ],          [&quot;A342&quot;, &quot;AGGATCCACAGGA&quot;],          [&quot;B652&quot;, &quot;AGGATCCACACTAGGATCCACACTAGGATCCACACT&quot; ]);}main();#--------------# FUNCTION: #     Align data in column based on column width (only for single row)# IN: #     Filehandle: File handle to send output (default STDOUT)#     Justifies:  List of justifying codes (right,center or left)#     ColsWidth:  List of columns&#39; width#     Data:       List of data to display (for single row)# OUT:#     none#--------------sub alignColumns($$$@){    my ($fileHandle, $justifies, $colsWidth, @data) = @_;    $fileHandle = *STDOUT if !$fileHandle;    my $totCols = scalar @$colsWidth;    my ($inline, $strLen);    my $finished = 0;    while(!$finished) {        $finished = 1;        # check each columns        #--------------        for my $colNum (0..$totCols-1) {            $data[$colNum] =~ s/^\s+//;            $strLen = length($data[$colNum]);            $inline = &quot;&quot;;            if($strLen &gt; 0) {                # check if data exceed column&#39;s size                #--------------                if ($strLen &gt; $colsWidth-&gt;[$colNum]) {                    $inline = substr($data[$colNum], 0, $colsWidth-&gt;[$colNum]);                    $data[$colNum] = substr($data[$colNum], $colsWidth-&gt;[$colNum]);                    # check if single word is splitted                    #--------------                    if ($data[$colNum] =~ /^[$not_separator]/o                           and $inline =~ /[$not_separator]$/o                           and $inline =~ /[$separator]/o) {                            if ($inline =~ s/(.+[$separator]+)(.+)$/$1/) {                                $data[$colNum] = $2 . $data[$colNum];                            }                    }                    $finished = 0;                } else {                    $inline = substr($data[$colNum], 0);                    $data[$colNum] = &quot;&quot;;                }            }            $inline =~ s/\s+$//;            # print data, justified            #--------------            print $fileHandle (&quot; | &quot;) if $colNum &gt; 0;            if($justifies-&gt;[$colNum] == ALIGN_RIGHT) {                printf $fileHandle &quot;%*s&quot;, $colsWidth-&gt;[$colNum], $inline;            } elsif($justifies-&gt;[$colNum] == ALIGN_LEFT) {                printf $fileHandle &quot;%-*s&quot;, $colsWidth-&gt;[$colNum], $inline;            } else {                # centered                #--------------                my $lenSpc = ($colsWidth-&gt;[$colNum] - length($inline)) / 2;                my $space = &quot;&quot;;                $space = sprintf(&quot;%*s&quot;, $lenSpc, &quot; &quot;) if $lenSpc &gt; 0;                printf $fileHandle &quot;%-*s&quot;, $colsWidth-&gt;[$colNum], $space.$inline;            }        }        print $fileHandle &quot;\n&quot;;    }}#--------------# FUNCTION: #     Align and display data in rows.#     Use function alignColumns() to align data in single row# IN: #     Filehandle: File handle to send output (default STDOUT)#     Justifies:  List of justifying codes (right,center or left)#     ColsWidth:  List of columns&#39; width#     Rows:       List of data to display (in mutiple rows / 2 dimensional data)# OUT:#     none#--------------sub alignRows($$$@){    my ($fileHandle, $justifies, $colsWidth, @rows) = @_;    for my $row (@rows) {        alignColumns($fileHandle, $justifies, $colsWidth, @$row);    }}#--------------# FUNCTION: #     Display data in numbered rows#     Notes - assuming first two rows of @rows are columns&#39; headers#     Use function alignRows() to align data# IN: #     Filehandle: File handle to send output (default STDOUT)#     Justifies:  List of justifying codes (right,center or left)#     ColsWidth:  List of columns&#39; width#     Rows:       List of data to display (in mutiple rows / 2 dimensional data)# OUT:#     none#--------------sub numberedAlignRows($$$@){    my ($fileHandle, $justifies, $colsWidth, @rows) = @_;    # add new column    #--------------    unshift(@{$rows[0]}, &quot;No.&quot;) ;      # add new column&#39;s header     unshift(@{$rows[1]}, &quot;-----&quot;) ;    # add new column&#39;s separator    my $count = 1;    my $num = 1;    for my $row (@rows) {        unshift(@$row, $num++) if $count &gt; 2;   # add number on each row        $count++;    }    unshift(@$justifies, ALIGN_RIGHT);      # add new column&#39;s justification code    unshift(@$colsWidth, 5);                # add new column&#39;s width    # call alignment&#39;s function    #--------------    alignRows($fileHandle, $justifies, $colsWidth, @rows);  }&lt;/pre&gt;
    </description>
</item>

        

<item>
    <title>Intelligently shortcutting $_-or-params, non-destructive-or-in-place function maker (Aristotle)</title>
    <link>http://prlmnks.org/html/559986.html</link>
    <guid isPermaLink="true">http://prlmnks.org/html/559986.html</guid>

    <description>
        &lt;p&gt;I often want to write short utility functions that do things like running a simple but frequently needed substitution on strings or the like. For these functions, I often want shortcutting behaviour: operate on &lt;tt&gt;$_&lt;/tt&gt; if not given a parameter, and operate destructively in-place if not asked to return values.&lt;/p&gt;&lt;p&gt;Writing functions that work like this is a real pain