Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Discipulus

by Discipulus (Priest)
on Jun 13, 2002 at 08:04 UTC ( #174111=user: print w/ replies, xml ) Need Help??

In the picture you can see my wonderful historical kawasaki motorbikes of serie GPZ Unitrack (1986 and 1984).

starting learning Perl as a game in a hot summer one year ago (ie 2001) on my linux system and now..
2003..trying to avoid learning vb administrating win32 with Perl..
..
2007..trying to avoid learning C# administrating win32 with Perl..
..
2013..trying to avoid learning powershell to manage w2k8r2 using Perl...
riding my Kawasaki GPZ 550
...April 12 2012: riding my Kawasaki GPZ 750..
...
29 July 2014 Discipulus became 668th in Saints in our Book

full page chat and last hour of cb


send UDP packets - ppc by vinsworldcom
defending eval string!
BrowserUk on GD image format
how GZIP compression works
Programming languages for multicore computers and gentle introduction to MCE and MCE by marioroy and also interesting thread started by karlgoethbier Threads From Hell #1 Threads From Hell #2 Threads From Hell #3 multiple threads to STDOUT threads and signals joining threads and order of things matter
odometer oneliner
seek speed
DBIx::PreQL aims is to simplify the horrendous task of maintaining dynamically generated SQL.
interesting info on stat file using the lonely underscore.
@_ and alias behaviour - many interisting things
autoincrement autodecrement explanation and history
about learning process
LWP check if Request was redirected
Spped up suggestion poit to the incredible MCE module
interesting thread about object oriented Perl that points to this subthread and to a very deep discussion about Perl object OO and Moose OOP how to (not) loose encapsulation
Perl on RaspberryPi
to valuable for a new Perl job by YourMother
good thread about test testing and habits. change a s‎crip‎t to be testable, caller info Tux abou refactoring code and Test driven design Testing methodology, best practices and a pig in a hut. by BrowserUk who point to http://www.sqetraining.com/sites/default/files/articles/XDD8375filelistfilename1_0.pdf Effective Automated Testing the sorry state of Perl unit testing framework
About windows inode here BrowserUk and others inodes found via gnuwin32 seems more recent of unxutils
about context and other links too If you believe in Lists in Scalar Context, Clap your Hands
about rounding integers here and BrowserUk's random cross platform. floating point addition and About Floating-Point Arithmetic and 1+1 != 2 and Humans have too many fingers Decimal Floating Point can arrive soon.
perl.exe vs wperl.exe here and wperl.exe and about temporary files on windows and SIDs or Unaltered child return code on Windows and win32 exit code after a crash guide
Multiplexing log output: Log4perl of the poors is mine prof of concepts to mimicry Log4Perl. Interstings also Loops's attempt found at Output to STDOUT and print last line to console
Optimising large files processing Recommendations for efficient data reduction/substitution application Using indexing for faster lookup in large file
about closures Merlyn column and Why closures where tye sythetize 4 types of progrmming, Corion pointed me to Kingdom of Nouns unrelated but quite related Why I like functional programming How A Function Becomes Higher Order and Real life examples of closures and also Closures Explained also tobyink on closures
switch to ssl for free
mass editi in Perl
Unicode utf-8 codepoints and graphemes and also The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) also when i will be able to understand all this post about Unicode i'll be happy in the new millennium Why am I having so much trouble and pain with UTF-8 in perl?
http://www.vagrantup.com/ replicate dev env
Passing an open handle to another process on win and about system 1 and system detached many interesting comments in http://www.perlmonks.org/?node_id=1101954 and salva's question and tye's answer about Windows and pipes that don't close.. quoting BrowserUk from hereOn Windows, parameters are passed to executables as a single string, so the list forms of system & open etc., join the list into a single string before calling CreateProcess(). Passing arguments to programs on Unix and Windows by afoken arguments to be protected from shell http://www.perlmonks.org/?node_id=1131761 http://www.perlmonks.org/?node_id=1039362 http://www.perlmonks.org/?node_id=925488 http://www.perlmonks.org/?node_id=621768 open in memry file - open to a reference - be aware of.. open a filehandle from an HERE doc
an interesting reading Exploring Programming Language Architecture in Perl found at Writing a Programming Language in Perl another intersting http://www.perlmonks.org/?node_id=77360 by Dominus
about threads on windows and an ufo Q module. and Adding parallel processing to a working Perl s‎crip‎t also see zentara words and links also another example here zentara's on IPC::Shareable and Parallel::ForkManager and Handling error on threads and ikegami's monitor child exit threads on Gtk problems and another Gtk threaded application Threads::Queue example threads and memory threads shared example Tk and forks links BrowserUk threads to search in a bi file neat fork example
just for fun (please do not feel offended, humor is humor..): if programming laguages were religions or cars other cars or car pictures or women or boats or drinks or bands or philosophers or natural language? humor geek hist
Fudge means a sweet.. but here you have a very detailed error reporting sub. using Log4perl instead of debugger About error handling IPC Open3 Catching errors by Ikegami
Tricks with DBI very old but usefull and GMAX DBI tutorial GMAX The fine art of database programming also Databases made easy by GrandFather
web programming for beginners and also the w3 validator or the web perfomance analyzer and why frames are not good (very ancient article)
Re: How to understand chapter 6 of Higher Order Perl?
One Zero variants_without_repetition combinatory calculus in aregex in the oha's answer.
Custom Sort An AoA intersting serie of replies about costum double sort.
colorized output
the x !! operator combo . found in conditional statements in list constructors ..but better is tye's ! $test ? () : ( ... )
Perl object memory overhead view the interesting replies.
Re: Ask for STDIN but don't pause for it
pack unpack tutorial and perl.pack.unpack.printf.cheat.sheet unpack is not so obviously the opposite of pack (padding) pack little endian big endian numbers
array and hash and other speed comparison
load module in BEGIN block ikegami's explaination of BEGIN sequence
The early history of Perlmonks
about app packaging and kirsle blog too http://www.kirsle.net/blog/kirsle/install-par-packer-on-windows an some good link here too decrypt a packed perl program Par pp and link to pp -x
The Dynamic Duo --or-- Holy Getopt::Long, Pod::UsageMan!
maze generator thanks fo funny to ambrus and choroba
Recursive Directory print view especially Laurent_R's answers.
Joel on software - The Process of Designing a Product
old but useful: behind the gui lives the shell
IP and subnets in given range
Perlmonks's World Map gently hosted by moritz
performance tunning of a lamp installation mysql swappiness problem
old utility to show ascii code
about our
lot of link about Tk in comments by monks ... but discovered Prima! and PerlQt
Re^3: Perl compiler request - flogging the dead horse! very interesting explanation of perl compile complexity
interesting bench about splitting long lines
Mojolicious::Lite +and jQuery +AJAX + Mojo::Template
Re: Pointers for building Perl off of Strawberry Perl. compiling a Perl under win
Perl was given to light ligther side of Perl search
check your s‎crip‎t against this
Damian Conway's ten rules for when to use OO
flip flop operator Perl Idioms Explained.. and Hidden features of Perl and also http://www.perlmonks.org/?node_id=525392 other flip flop considerations and links
Teaching perl: Re: How to teach perl to novice programer and Re: What is the best way to master perl (do your homework)
About new modules: perlnewmod that links also to this one... Create a ppd module distribution and also Corion's answer a lot of links about naming and new modules and about installed modules About Packages and modules namespaces Writing Solid CPAN Modules require "shared.pl" with use strict; points to Include subs from different perl file A brief question about testing/best practices testable code - S‎crip‎tor and Programmers skimmable code Exporter and Exporting-Without-Inheriting-from-Exporter
poem on strict... The strictures, according to Seuss Levels of strictness and compatibility when use -w or use warnings module related and veri interesting
Plack Dancer Dancer2 et alia: Understanding benefits of Plack PSGI, Plack et.al. and also Dancer2 sessions under Plack and http://blog.kablamo.org/2014/04/08/read-plack-1/ also Beginner's guide to Dancer Dancer calendar 2010 2011 2012 2013 few things on Dancer2 SawyerX speacks about Dancer2 and CGI must die! larsen writes about plack Dancer2 sessions under Plack About sessions and modules to do it How to make ajax requests in Dancer2 Write a Filehandle w/Dancer2 Dancer2 - How to loop over a ref to a HoH Dancer & Plackup - Redirect not refreshing page data Bizarre Dancer encoding behavior Need tipps for identifying utf-8 problems with Dancer and MySQL Beginner's guide for Perl Dancer contains internet introduction too Current Dancer route Your Mother about recicling an existing CGI in plack free Dancer Hosting (not tested) and psgi links and plack ones by Miyagawa and tobyink on deploying strategies of psgi app and Plack and multiple domains which point to this one and mount_multiple_apps_with_plack http://www.josetteorama.com/all-about-dancer-interview-of-sawyerx/ part one two and 3 and last also about session signed cookies with Plack form from CGI to Dancer and Template Toolkit some links about basic internet Jeffa Dancer example Plack debugger infos Plack modperl FASTCGI etc also link to plack for beginners Multiple plack apps and deployment Mojolicious::Lite slides Web Apps - small examples and guidance
How can I visualize my complex data structure?good post about dumping complex datastructure, and comparison on Perl serialization options also GrandFather note

Note that $, % and @ don't tell you what type variables are, they tell you what type of thing an expression returns. So $ref returns a scalar which may be a reference to an array or a hash. @$ref and @{$ref} return arrays (they are equivalent) by dereferencing $ref. The {} version is much clearer (and often required) when the expression used to get the reference is complicated.


SOAP, WSDL, XML service/clientgood post (seems) on WSDL links about soap and wsdl
How do I mix up Perl and jQuery (for beginners) lot of examples Perl + jQuery
XML "If you need to deal with XML, first, we’re very sorry." b d foy http://www.effectiveperlprogramming.com/2011/07/rewrite-xml-with-xmltwig/ and http://www.effectiveperlprogramming.com/2010/03/process-xml-data-with-xmltwig/ and http://it-is-etc.blogspot.it/2012/07/perl-how-to-manipulate-xml-files-using.html and http://perlmeme.org/tutorials/parsing_xml.html speed comparison http://www.robinclarke.net/archives/xml-parsing-with-perl mirod schratchpad and Re: Another simple XML Twig question and http://www.xml.com/pub/a/2001/03/21/xmltwig.html ambrus's Do not reinvent the wheel: real-world example using XML::Twig and also http://perl-xml.sourceforge.net/faq/ and choroba about XML parse an infinite strem with XML::Twig and LWP -- complete example with server too
Davido's precious regex tester is now here also onther testing site suggested by Eily also, anonimously suggested, rxrx and this one and this other one and also VRegExp or 7stages of a regexes user and http://www.perlmonks.org/index.pl?node=sexeger and http://www.perlmonks.org/index.pl?node=Array%20One-Liners and Using Look-ahead and Look-behind 7 Stages of a Regex User two-dimension regex
lot of links about debugging Perl code and Use strict warnings and diagnostics
Tartaglia's Pascal's Triangle: mine Pascal Triangle Pascal's triangle... where you can find perl -e "while((@_=(1,map$_[$_-1]+$_[$_],1..@_))<=$ARGV[0]){print qq(@_\n)}" Binomial Expansion http://mathforum.org/workshops/usi/pascal/pascal.links.html and another interesting page see also The Oldest Plays the Piano Explain one liner for fibonacci and Explain Fibonacci one-liner ?? also test of primality Another primality a quasi sieve My big tk program about Tartaglia's triangle choroba fastest prime check Sieve of Erathostenes obfu
big integer 64bit caveats
SSH2 demo
Use strict warnings and diagnostics or die
ooh, oh, ohh is still alive!
from Why do people say 'Perl' is dead?!?!
speed comparison 2012
http://nerds-central.blogspot.it/2011/03/perl-still-dominates-over-python-ruby.html and choroba mentioned TIOBE in chat; never eard.
refactoring CGI appsRe: Refactor CGI::Application and supporting scrits difference between library and framework Re: What does Mojolicious do exactly and is it right for me? IIS 7.5 Re: can Perl-CGI run persistently on Windows 2008 with IIS 7.5? how? Activestate http://docs.activestate.com/activeperl/5.16/bin/ap-iis-config.html and iis7.5 http://community.activestate.com/forum/activeperl-iis-75 Perl on IIS 7 and win2k8 header examples: Need help in translating the following php code to perl a lot of links about CGI and web related stuffs Perl and CSS (boostrap perlcritic.css and other) Strawberry Perl on IIS 6
MOdern replace of SSI Re^3: A modern Perl repalcement for Apache Server Side Includes?
Re: Writing portable code writing portable code OS independent perl s‎crip‎t and Re: Command line arguments not passed in Win7 ( regqueryperl.bat ) and Question on Strawberry's Portable .bat file and also variables substitution in cmd.exe and Re^2: Dangerous Characters for system calls also relocate Perl 5.20. Also see the /D switch of cmd.exe that point here Portable win32 perl application without PAR::Packer where anonymous point explain portability of ActiveState Perl and here about win file system redirection 32 64bit madness
mar 2013 - About BEGIN blocks: Re: Returning information from BEGIN Re^3: BEGIN and compile-time Never lock $0 inside of a BEGIN block Re: Perl templating/macro creating using 'BEGIN'... Re: BEGIN block and prototyped subroutines Re: BEGIN vs initialization __DATA__ used in BEGIN and Is this BEGIN construct supposed to work? and about UNITCHECK in my check modules used by a s‎crip‎t and their version module caller Who called Perl $0 in @INC
Re: console adventure game to html mod_perl version about gaming
Using the DATA file handle for ARGV DATA, ARGV and typglob trick very well written intro and the recent Why does Perl have typeglobs? and not useful but intersting magic used by $^T in this post. tye explain that * is the sygil for FH Re: Why don't file handles have sigils? (*) Removing CODE slot in typeglob http://www.perlmonks.org/?node_id=1116851 http://www.perlmonks.org/index.pl?node_id=331262 symbol table by dada (italian) https://www.safaribooksonline.com/library/view/advanced-perl-programming/0596004567/ch01.html ysth about symbol table the same doubt i had page 130 typeglob/symbolic reference question perl-iterate-over-a-typeglob pad walker example symbol table manipulation Perl Internals - references and symbol table get the list of methods and variables in a package Devel::Symdump and symbol table woes Dominus about scope my question about symbol table, typeglob.. where Lanx point to dumping lexical filehandles inspect packages to spot datastructure definition by AnomalousMonk
Perl White Magic and one liners and A gentle introduction about Perl command line flag and a column by Merlyn at stonehenge and which oneliners monks use

perl idioms

stolen from busunsl's homenode
  • slurp a file:  my $contents = do { local (@ARGV, $/) = $filename; <> };
  • set even elements of @list to 'bla':  $_ % 2 or $list[$_] = 'bla' for 0..$#list;
  • getting indices sorted by value: my @indices = sort { $a[$a] <=> $a[$b] } 0..$#a;
  • initialize hash elements: @hash{@array} = (1) x @array
  • assign empty string defaults: $_ = '' for grep ! defined ( $foo, $bar, $baz );
  • blank padding: $str = pack('A40',$str);

some cool use of Perl



Posts by Discipulus
CPAN Namespace Navigator in Cool Uses for Perl
1 direct reply — Read more / Contribute
by Discipulus
on Nov 25, 2014 at 06:23
    CPAN Namespace Navigator is an interactive program that let you to navigate all namespaces on CPAN.
    The idea born when i read that before upload something to CPAN is better to explore existing modules, but when i asked here in the chat how to browse it i discovered that ther is not a real exploration program to do it.

    So the challenge was to hack directly the fomous file 02packages.details.txt that we receive (gzipped) when we search some module with some CPAN client. I used Term::ReadLine not without some headache.

    I decided (unwisely) to eval directly the data received to build up a big HoH with the whole hierarchy of CPAN modules and reletad infos. As suggested (wisely) by ambrus and yitzchak i looked at tye's Data::Diver and on my own at an ancient and unmaintained Data::Walker one.

    I was not able to bind Data::Diver at my will to add to the structure others infos like parent namespace or version, so i reinvented that wheel evaluating everything by myself.

    Surprisingly it worked.

    This is the usage and the navigation commands available during the navigation:
    USAGE: cpannn.pl [02packages.details.txt] NAVIGATION: . simple list of contained namespaces .. move one level up + detailed list of contained namespaces * read the readme file of current namespace ** download the current namespace's package ? print this help TAB completion enabled on all sub namespaces cpannn.pl by Discipulus as found at perlmonks.org
    And here you have the code, finally crafted after 37 steps of development.


    HtH
    L*

    update: take a look also at Re: Autocomplete in perl console application
    There are no rules, there are no thumbs..
    Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.
Tk Tartaglia's triangle fun - Pascal's triangle fun in Cool Uses for Perl
2 direct replies — Read more / Contribute
by Discipulus
on Jun 17, 2014 at 12:56
           Dedicated to my father who studied the other Tartaglia
    After more then one month of sparetime works and 35 subversion i'm very happy to present you:

    16 fun experiments with the Tartaglia's triangle

    This is a Perl Tk program that shows many of the properties of such incredible triangle: you can modify the aspect of the triangle itself and of the output window and of the help pages too.

    In Italy the name of the arithmetic triangle is dedicated Tartaglia so I want to present with this name.

    I'm not a mathematician and the math used in the code is something late Middle Age, but works.

    If someone wish to improve this program i will be very happy: inernal math used, better explication in output windows, or even typos spot(i'm not english native, as you can guess) or suggestion are welcome. In fact i wish this program to be used in educational context.

    Have fun!

    L*


    Update 1/07/2014: commented lines 188-190 and 555 (printing debug info for windows dimensions and positioning).

    L*

    There are no rules, there are no thumbs..
    Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.
Tk image resizer in Cool Uses for Perl
1 direct reply — Read more / Contribute
by Discipulus
on May 05, 2014 at 07:08
    Hello monks,

    was a rainy saturday and i need some resized images for a new website (a Dancer2 one).. but i'm digressing.
    This script globs all jpg images in the current directory and creates one or more resized ones with new names. EXIF data are cleaned in new images whilst you can view some of them, for your convenience, in the preview of the original image.

    Only argouments accepted are string in the form width x heigth x descr as in 1204x768xBig
    You can specify more then one format passing, for example: 1204x768xBig 640x480xMed 200x100xMin
    The description in the string is optional: if not present is used the given ratio: 1204x768 wil be appended to the file name given.

    Using Image::Resize the ratio is maintained for the original photo, ie only the width will be used, while the height will be adjusted as needed.

    The code is redundant and somehow ugly, but Perl does not complains about this..

    HtH
    L*

    There are no rules, there are no thumbs..
    Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.
check modules used by a script and their version in Cool Uses for Perl
2 direct replies — Read more / Contribute
by Discipulus
on Apr 03, 2014 at 06:26
    another CUFP or better WICDWMBP (what i can do with my baby Perl)..
    Reading this post i'm started wondering if there was a way to wrap an existing script and grab modules it uses without exucuting it.
    Obviously the answer or part of it was in the monastery: here
    I very liked the
    perl -d:Modlist=options script.pl perl -MDevel::Modlist=options script.pl # equivalent
    part but, unfortunately it executes the script.pl
    Also liked the tachyon-II hack, but you have to edit the script.pl and i'm too lazy.
    No hope to use $^C = 1 as pointed wisely by shmem

    The UNITCHECK do the trick! Never known it seems quite usefull for this task: read about it

    #!perl #use strict; #commented to not pollute %INC #use warnings;#commented to not pollute %INC my $file = $ARGV[0]; my $content = do { open my $fh, '<', $file or die $!; local $/; <$fh> +}; my $begin =<<'THEEND'; UNITCHECK { no strict; # access $VERSION by symbolic reference no warnings qw (uninitialized); print map { s!/!::!g; s!.pm$!!; sprintf "%-20s %s\n", $_, ${"${_}::VERSION"} } sort keys %INC; exit; }; THEEND eval $begin.$content; print $@ if $@;
    Enjoy the results!
    HtH
    L*

    UPDATE 9 april 2014: BE CAREFULL, as stated by davido and also by LanX in other post, BEGIN blocks are executed anyway. In fact BEGIN blocks come first, in order of definition, then come UNITCHECK blocks and, being that block prepended to the original code in the above program, it will be executed just after the last BEGIN block and just before any UNITCHECK defined in the original program passed in via @ARGV. In the case of perl -c -d:TraceUse script.pl all the BEGIN UNITCHECK CHECK blocks are executed.

    Here two examples to demonstrate where the -c ends his operations (a simplified version of 16 pillars of wisdom):
    perl -c -e "BEGIN{print qq(1-begin\n)}; UNITCHECK {print qq(2-unitcheck\n)}; CHECK {print qq(3-check\n)}; INIT {print qq(4-init\n)}; print qq(5-main\n); END{print qq(6-end\n)}" __OUTPUT__ 1-begin 2-unitcheck 3-check -e syntax OK # the same code without -c __OUTPUT__ 1-begin 2-unitcheck 3-check 4-init 5-main 6-end
    L*
    There are no rules, there are no thumbs..
    Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.
Automatic chrome extension generator in Cool Uses for Perl
No replies — Read more | Post response
by Discipulus
on Mar 25, 2014 at 17:27
    Well, I needed to add few extensions to the browser and i ended with this...
    It generates a working chrome extension with only a context menu that acts as 'Search with <your search engine>'.

    You'll call the script with only 2 args: a_description and a partial URL
    as in extgen.pl Cpan_search http://search.cpan.org/search?query=
    Then you point chrome to chrome://extensions/, check 'Developer Mode' and choose 'Load an unpacked extension' and browse to early created folder containing the extension.

    Here is the code:
    #!/usr/bin/perl use strict; use warnings; my $folder = $ARGV[0]; my $url = $ARGV[1]; (my $descr = $folder) =~ s/_+/ /g; my $longname = 'Perl genarated extension - '.$descr; mkdir $folder or die "Cannot create $folder: $!"; chdir $folder or die "Cannot enter $folder: $!"; # the manifest open MANIF, '>', 'manifest.json' or die "Cannot open a file to write i +n: $!"; my $manifest = '{ "manifest_version": 2, "description": "'.$descr.'", "background": { "scripts": ["background.js"]}, "name": "'.$longname.'", "permissions": [ "contextMenus", "tabs" ], "version": "1.0" }'; print MANIF $manifest; close MANIF; # the jscript open JSCRIPT, '>', 'background.js' or die "Cannot open a file to write + in: $!"; my $background ='function customfunc(info) { var searchstring = info.selectionText; chrome.tabs.create({url: "'.$url.'" + searchstring}) } chrome.contextMenus.create({title: "'.$descr.'", contexts:["selection" +], onclick: customfunc});'; print JSCRIPT $background; close JSCRIPT;
    There are no rules, there are no thumbs..
    Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.
Multiplexing log output: Log4perl of the poors in Cool Uses for Perl
No replies — Read more | Post response
by Discipulus
on Oct 21, 2013 at 03:03
    The 'Cool users for Perl' is a little intimidating for this snippet..
    I was writing a program with the strictly use of core modules only and i was thinking to add the log functionality.

    I looked at Log4Perl and wow... what a suit of features!I decided to try replicate some features: first the multiplexing of the output.

    To use this you need to declare two hashes: the first is for handlers. It contains as key as you wont. Every key contains a three elements array: the glob of an already opened filehandle, the error level for this handler, and an anounymous sub to compose the final logline for this handler. Theese subs will receive two elements: the level and the message (ERROR, 'Cannot read').

    The second hash is a dispatch table that merely filter unwanted message for a particular handler.

    The small sub do an ugly cut on the incoming message and call some code for each handler defined.

    As good side note you can change the level of an handler at runtime.

    Comments and improvement welcome.

    #!perl use strict; use warnings; $|++; # open some FH you'll use, handler 0 now is the already opened STDOUT open (LOG, '>','log-multiple-output.log') || die; open (BIGLOG, '>>','biglog.log') || die; # handlers: GLOB, LEVEL, COMPOSITION SUB receiving $lvl, $msg my %loghdl = ( 0 => [ *STDOUT, 'ERROR', sub{ return $_[0]."> $_[1]\n"}, ], 1 => [ *LOG, 'INFO', sub{my(undef, undef, $line) = caller(2); return $_[0].">".(scalar localtime(time)).' "'.$_[1].'" lin +e '.$line."\n"}], 2 => [ *BIGLOG, 'ERROR', sub{my(undef, undef, $line) = caller(2); return $_[0].">".(scalar localtime(time)).' "'.$_[1].'" lin +e '.$line."\n"}], ); # the filters declaration my %wanted =( DEBUG => sub { my ($to,$dbglvl,$action) = (shift,shift,s +hift); grep (/$dbglvl/,qw(DEBUG)) ? print $to $ac +tion->(@_) : 0; }, INFO => sub { my ($to,$dbglvl,$action) = (shift,shift,sh +ift); grep (/$dbglvl/,qw(DEBUG INFO)) ? print $t +o $action->(@_) : 0; }, WARNING => sub { my ($to,$dbglvl,$action) = (shift,shift,sh +ift); grep (/$dbglvl/,qw(DEBUG INFO WARNING)) ? +print $to $action->(@_) : 0; }, ERROR => sub { my ($to,$dbglvl,$action) = (shift,shift,s +hift); grep (/$dbglvl/,qw(DEBUG INFO WARNING ERRO +R)) ? print $to $action->(@_) : 0; }, FATAL => sub { my ($to,$dbglvl,$action) = (shift,shift,s +hift); grep (/$dbglvl/,qw(DEBUG INFO WARNING ERRO +R FATAL)) ? print $to $action->(@_) : 0; }, ); ## the sub cut the head of the incoming string sub ulog { my $msg = shift; chomp $msg; (my $cmd = $msg)=~s/\s+.*//g; $msg=~s/^$cmd\s+//; $cmd = uc $cmd; foreach my $hdl (sort keys %loghdl) { exists $wanted{$cmd} ? $wanted{$cmd}->( @{$loghdl{$hdl}},$cmd,$msg) : print {$loghdl{$hdl}->[0]} 'Unknown logevel>'.lc ($cmd).' '.( +lc ($cmd) eq $msg ? '' : $msg)."\n"; } } #EXAMPLE of use ulog 'Eccolo qui'; ulog ('DEBUG debbuuuugga'); ulog ('Debug debbuuuugga'); ulog ('INFO infohere'); ulog ('WARNING warn!! you are not authorized'); ulog ('ERROR unable to read'); ulog ('FATAL cannot find Perl..'); print "\nchanging lvl to debug..\n\n"; $loghdl{0}->[1]='DEBUG'; ulog 'eccolo qui'; ulog ('DEBUG debbuuuugga'); ulog ('debug debbuuuugga'); ulog ('INFO infohere'); ulog ('WARNING warn!! you are not authorized'); ulog ('ERROR unable to read'); ulog ('FATAL cannot find Perl..');
    I hope someone can find this useful.

    L*
    There are no rules, there are no thumbs..
    Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.
Tartaglia's triangle in Cool Uses for Perl
3 direct replies — Read more / Contribute
by Discipulus
on Apr 02, 2013 at 08:02
    ok hdb have burned me on time..

    This is my first math script. Any math or Perl suggestion welcome!
    #!/usr/bin/perl use strict; use warnings; { my @tartaglia ; sub tartaglia { my ($x,$y) = @_; if ($x == 0 or $y == 0) { $tartaglia[$x][$y]=1 ; return 1}; my $ret ; foreach my $yps (0..$y){ $ret += ( $tartaglia[$x-1][$yps] || &tartaglia($x-1,$yps) ); } $tartaglia[$x][$y] = $ret; return $ret; } } sub tartaglia_row { my $y = shift; my $x = 0; my @row; $row[0] = &tartaglia($x,$y+1); foreach my $pos (0..$y-1) {push @row, &tartaglia(++$x,--$y)} return @row; } for (0..5) {print join ' ', &tartaglia_row($_),"\n"} print "\n\n"; print &tartaglia(3,3),"\n"; my @third = &tartaglia_row(5); print "@third\n";
    there are no rules, there are no thumbs..
WebTimeLoad 0.15 scan and time website using LWP::Ua in Cool Uses for Perl
2 direct replies — Read more / Contribute
by Discipulus
on Jun 06, 2011 at 05:22
    while learning few of the many things about LWP::* modules I wrote down this program to time and test websites.
    The main goal is to report the download speed of one (or more) webpage and eventually some other information. This is accomplished by running the program in the simplest way:
    webtimeload.pl -u www.perlmonks.org
    One of other goal was to distinguish the content served by same website from content coming from outside the main site.
    The program can load not only http site but every protocol supported by LWP itself (with the -p --protocol switch). You can repeat the download using the -c --count switch sleeping as you wish between requests with the -s --sleep switch. You can control the LWP::Ua timeout with the -t --timeout switch and print the headers of the main response with the -h --header switch

    Most of the flexibility is obtained via the -v --verbosity switch: with a value of zero, the verbosity is quit null giving a one line output usefull for post processing. The next step is -v 1 which is hte default give up a short summary of the resposnse and a total of the download time. Verbosity 2 add more info about the server response and subtotals for included content.Verbosity 3 add detailed information (url, bytes, seconds) for each item downloaded.

    TODO(please help me to complete)
    • Take track of redirections
    • be exhaustive parsing the html (is body img src frame sufficient?)i'm not sure to grab background


    UPDATE: new version available below!
    UPDATE feb 2013: new version available below!

    there are no rules, there are no thumbs..
when no ping say 'moo!' in Cool Uses for Perl
4 direct replies — Read more / Contribute
by Discipulus
on Feb 25, 2009 at 07:13
    aah ahh not so cool but handy maybe!!
    linux peoples can rearrange easely.
    run as follow: Aping.pl -i 10.0.0.1
    or without args to get help

    Lor*
    #!perl use strict; use warnings; $|++; use Getopt::Long; use Win32::Sound; my $sleep = 60; my $conteggio = 4; my $echook = ( $conteggio - 1 ); my $alarmnum = 3; my $sound; my $volume = 100; my $host; &aiuto() if ( ! GetOptions ( 'ip=s' => \$host, 'sleep=i' => \$sleep, 'conteggio=i' => \$conteggio, 'ok=i' => \$echook, 'alarm=i' => \$alarmnum, 'play=s' => \$sound, 'volume=i' => \$volume, ) or ! $host ); $alarmnum = 3 if $alarmnum < 1; if ( $echook > $conteggio ){ $echook = $conteggio-1 } if (defined $sound && !(-e $sound)) {$sound = 'crow.wav'} while (1){ sleep $sleep; my $ok = &controlla($host); if ($ok < $echook){ for (1..$alarmnum) { &suona() } print "ERROR !\n"; } else {print "OK $host\n";} } sub suona { if (defined $sound && -e $sound) { Win32::Sound::Volume($volume,$volume); Win32::Sound::Play($sound); } else {sleep 1; print"\a\a"} } sub controlla{ my $ok =0; open CMD,"ping -n $conteggio -l 1 $host 2>&1|"; while (<CMD>) {++$ok if $_ =~/$host/;print"."} close CMD; return $ok; } sub aiuto { print <<EOA; USAGE OF $0: $0 -i 10.0.0.1 [-sleep n] [-conteggio n] [-ok n] [-alarm n] [-play + file.wav] [-volume %] -i 10.0.0.1 ping specified IP every 60 seconds 4 times expecting 3 positives repl +y or play 3 system bell during 3 seconds --ip=10.10.0.1 --sleep = 30 --conteggio = 10 --ok = 5 --alarm = 20 -i 10.10.0.1 -s 30 -c 10 -o 5 -a 20 same of above EOA exit 1; }
Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (11)
As of 2015-08-03 20:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The oldest computer book still on my shelves (or on my digital media) is ...













    Results (55 votes), past polls