 |
User since: |
Jun 24, 2000 at 20:36 UTC
(25 years ago) |
Last here: |
Oct 03, 2025 at 17:58 UTC
(1 day ago) |
Experience: |
3245
|
Level: | Curate (13) |
Writeups: |
314
|
CPAN ID: | SOMIAN |
Location: | Buffalo CITY / New York STATE / U.S.A. NATION / North American CONTINENT / Western HEMISPHERE / Terra PLANET / Sol SYSTEM / MilkyWay GALAXY / "local" GROUP / Virgo SUPERCLUSTER |
User's localtime: |
Oct 04, 2025 at 20:34 EDT
|
Scratchpad: |
View
|
For this user: | Search nodes |
|
about this image: |
This is a visual fingerprint (a "visprint" as it's called)
— an image generated using fractal maths —
representing my GnuPG key fingerprint
(postprocessed in ImageMagick). |
Welcome to the home node of The Unreasonable Man! He goes by Soren, Sorentino, "somian", "amphibole", Soren Andersen)
“The reasonable man adapts himself to the world; the unreasonable one persists in trying to adapt the world to himself. Therefore all progress depends on the unreasonable man.” — George Bernard Shaw
Other Favorite Quotes
"[André Malraux said] Do what you believe you must and leave the interpreting of it to others."
"[This] seemed to me to summarize his personal philosophy. How true this is. Don't be distracted by the
carping of bystanders, their irresponsible attitudes, their self-serving, cowardly words and actions."
— Daisaku Ikeda on a dialog with André Malraux
A little quote about religious tolerance, which I see as pertaining to
the tendency of some Christians to shout "Persecution!" rather often nowadays:
"We respect the right
of everyone to believe whatever they like. ...
But there are two important limits to religious tolerance. First, I have no
right to legal protection against your scepticism, criticism or ridicule.
Religion is too powerful a force, and is too often a cause of injustice or
evil, for it to be immune from discussion and debate."
—
David Pannick QC
“Perl is the portable distillation of
the UNIX philosophy."
—
Scott McMahan
"Write documentation as if whoever reads it is a violent psychopath who knows where you live."
—Steve English, as quoted by Peter Langston
but do not say later that you didn't have access to those views, carefully
explained ;-]>
I learned some Perl and became a CPAN Author:
[...]AUTHORS/ID/S/SO/SOMIAN/
"... people who condemn others simply on the basis that the target of condemnation is "angry" or "frustrated" are using a false premise as a basis for their condemnation. Anger is not, by itself, a transgression against society, or the Monastery."
The most reasonable of suggestions has been made
in Dealing with An(?:no|on)ytroll by tirwhan. It
deserves serious thought.
You will see formatting oddities on this node. These show as visible HTML formatting tags. The reason is not carelessness; instead, after this node was
created, the parser for Perlmonks nodes changed such that style=... in tags is no longer accepted.
A short rant
One thing that I've noticed in my time spent chatting in the cb here at Perlmonks is that the level of ethical sophistication amongst a few of my fellow cb'ers can be terribly low. I make this generalization because there's one prime point of all ethical systems that I can feel any respect for, and that is:
Might does Not make Right
But it is clear that among the cb'ers are those who don't understand this. They have an enormous blind spot when it comes to issues in the workplace or the Perl (or other kind of) hacker community. Maybe it's a generational thing; I'm in my 40s and many Monks are in their 20s. I think the times are shaping young people to have much lower sensitivity to this. Most are very quick to point out the shortcomings of political leaders but very few seem able to see that abuse of privilige and power plays a big role close around them in their everyday lives.
There are two kinds of social power generally at work in our world:
- Individual Despots
and
- The Despotic Mob
Both these exert their influence generally (not always) to the detraction of good in the lives of human beings, to the enhancement of evil. People seem to regard the exercize of power by individuals like irc ops as some form of divine right, which is fine as long as such people who think this way don't try to pass themselves off as freedom-loving people. Furthermore: there seems to be a general assumption that if a person has contrary views to an irc #channel-op or a Perlmonks God, they are automatically wrong. This is childish, immature, dangerous and pathetic.
Just as bad is the pattern wherein supposedly intelligent people automatically assume that the person saying a new thing that insults (in their view) or challenges a comfortable dogma, or other item of "social consensus," is automatically wrong.
The only positive change that has ever taken place in the world has come about because of alienated, despised malcontents who dared to speak truth to power. The only kind of human being truly worth honoring is one who can summon the personal courage to speak truth to power, on whatever level or in whatever form it takes (embodied as either the despot or the mob). No-one lives a worthwhile life without ever falling afoul of some embodiment of power, sometime during their lives. The rest of humanity live like
sheep, and no society that deserves to be remembered by history erects monuments of honor to sheep.
When a person gets banned in irc or otherwise "punished" somehow in any kind of hacker social context, they fairly often deserve it because their actions have been contrary to the general good of the group. But not always. This distinction between "always" and "not always" is the difference between the destruction of the world and its salvation. It is everything. Not understanding this is the distinction between an ignorant person and a real citizen, whether of the Happy Realm of Hacking Free Software or of the World.
From the Wikipedia entry for Internet Troll we see this quote:
[Likewise,]
accusers are often motivated by a desire to defend
a particular Internet project, and references to an Internet user as a
troll might not be based on the actual goals of the person so named. As
a result, identifying the goals of Internet trolls is most often
speculative.
The use of the term "Troll" on Perlmonks by a certain group of people is an
example of something like what's described above. It reflects not on the
accused person but on the accusers, who are
misusing a type of peer group -based power (being the Despotic Mob)
to exercize coercion against someone whose
aims are, as many others see, not those of a troll at all. The very best
that can be said of such misuse is that the accusers are engaging in
reckless and irresponsible speculation. The worst is that they themselves
are far more despicable than any "Internet Troll", that they are in fact
aiming to give themselves the twisted pleasure of seeing their group power
effectively deny another participant the option of
continuing to engage in a reasonable relationship with the site, community
or project in question.
One can only feel pity for people living with the kind of impoverished
inner lives and distorted emotional personalities that would derive pleasure
from such a thing,
but unfortunately the modern world at least, with its intense pressures
and demands, often gives rise to such it seems.
I don't see posts by Anonymous Monk beginning at 6:30pm on 7 Dec 2005,
by using CSS to override display settings. The texts of postings of any nature
by any non-existing (Anonymous) Monk are invisible for me. This is a measure
that I've taken until such time as the preferred solution comes to pass (the
preferred solution being: the Perlmonks site no longer allows Anonymous
posting at all).
A side note:
The application at cb60 is the
only cb history interface that is currently working (to my knowledge) at
the time of this writing, and is the only one that can be configured to
ignore users as the live chatterbox can.
There's a particularly annoying kind of conduct that very frequently
takes place and lands users who commit it on the following list. This
consists of coming into the chatterbox with a minimal but strange-sounding
question - one that rings "warning bells" for some of the experienced
Perl users. When it is suggested that more information is needed because
the approach seems dubious (perhaps based on a mistaken understanding
of how something in Perl works), such an individual committing this
type of annoyance then leaves in a huff, saying something like Thanks
for the kind help in a sarcastic and injured way that is intended
to cause guilt feelings.
This is playing the "Newbie Victim of Mean Monks"
card, and it is not only stupid, and not only pathetic,
but also wrong - because the chatterbox or Perlmonks in general
is a place where many give of their time to try to help less experienced
Perlers. These volunteers don't need to put up with that kind
of childishness, the attempted emotional manipulation and tantrums;
and in my opinion, should not put up with it.
Again, it is (in my opinion), really ok to insist on minimum standards of
mature behavior in order to qualify for help or attention at Perlmonks.
Perl Tips, Observations, and Experiments
I use both Free Software Operating Systems and the proprietary Microsoft Windows OSes.
Obviously I prefer to spend more time on the former (my favorites are Ubuntu and its
parent distribution, Debian). On MS Windows I use both ActivePerl and the new Win32
Perl that's being called
StrawberryPerl.
I often build my own Perl installations from source, as well.
The quality of the user experience one has with the MS Windwoes OSes is highly variable.
Some users find little lacking in it and some are driven crazy by it. One inclination
that is not well-served by Microsoft is the desire to use the CLI (Command-Line Interface,
but if you are here reading, you knew that ;-) …and so I rely on the long-lived
and community-supported
Cygwin
environment (this is important: Cygwin is supported by volunteers; do not act
like a petulant spoiled brat if you go asking for support {if you happen to try Cygwin
out}; if you do, you will just be ignored). Cygwin provides a port of Perl that tracks
the major release cycle of mainstream Perl and "acts like" Perl running on a unix OS
platform. Cygwin also provides the Bash shell and many other GNU userspace components
that are common to all GNU/Linux and other free unix OSes.
Because I have acquired years of experience using Perl on MS Windwoes, I do not have
the oblivious outlook about file name extentions that is customary from users who do
only work on unix platforms. My decision is to name Perl programs with a .plx
extention which disambiguates these files from those containing Perl library code. I
use the appropriate MS Windows commands (from the CMD.exe cli) to create the right
Registry settings so that the files named with .plx extentions are
associated with the perl executable.
A smattering of Useful Tips for PerlMonks, especially new ones
Ripped off from busunsl's node:
Link types at PM (because I tend to forget :-):
- [id://] a node's id (numerical value)
- [cpan://] searches CPAN
- [kobe://] is an alternate means of searching the CPAN (contrasted with the [cpan://] tag)
- [jargon://] searches the Jargon file hosted at the University of Amsterdam.
- [doc://] searches perldoc.perl.org: the
idea here is to provide a way of linking to more current Perl documentation
than what Perlmonks can maintain.
- [pad://] is a shortcut to a user's scratch pad
Monks Solemn Intonement:
righteousness ()
{
perl -e'
print "The troublesome entities, irksome to Monks:\n "
, ( join " and ",
map{
sprintf qq{$_ is safe as }.q{&#}.qq{%d;}, ord ;
} qw/[ ]/ )
, "\n";
'
}
n.y.p.m.blue
– my PerlMonks color theme for CSS-supporting browsers – is now listed and maintained on this node.
This list is of modules that I'm not currently using for anything but that I think I
might want to at some future time
A little parts bin of useful HTML entities for doing PM node markup
"[" left sq brkt [ [
"]" right sq brkt ] ]
"<" left angle brkt > < or <
">" right angle brkt < > or >
"mdash" em-dash — —
"ndash" en-dash – –
"lsquo" left single quotation ‘ ‘
"rsquo" right single quotation ’ ’
How I am creating ordinary paragraphs for Perlmonks node writeups these days:
perl -MText::Wrap='wrap,$columns' -MText::Textile=textile \
-lp000we \
'INIT{$Text::Wrap::unexpand=0; $columns=88; print qq/\n/. q[-]x88 .
+qq/\n/ };
s{\cM?\cJ} [\cJ]g;
$_=wrap(q[],q[],textile($_)).$/;
s{<br />} []g;' </dev/clipboard
This should work fine in a MS Windows CMD shell too, with the alterations that
(a) all single quotes around the -e script and perl flags are changed to double quotes,
and (b) the line-continuation backslash/newlines are removed.
·Assorted Perl Stuff, and platform-specific notes·
Which and where is
“Some::Perl::Module”
(finding VERSION and location of a Perl module):
Preface:
Depending on your OS and your work habits / preferences, you
might want to use a Unix sh means of wrapping the Perl code
implementing this technique (second thing below), or you might need a MS
Windows console helper (in the form of a DOSKEY macro,
shown immediately below). I've named this critter different things
in different manifestations on different machines at different
times ... but now I am aiming to settle on it being named
PMTEST.
PMTEST=perl -le "do{$modn=$_;s!::!/!g;$_.=q[.pm];do{print qq[$modn is
+not installed.];next} unless eval qq#require(\"$_\");1# && !$@;$modv=
+defined(${$modn.q[::VERSION]}) ? ${$modn.q[::VERSION]}:q{[version und
+efined]};$numtyp=2>$modv=~tr/.// ?'%s':'% 6d';printf qq[ %-*s $numty
+p in %s\n],(length>30 ? 5+length:15+length),$modn,$modv,$INC{$_}}for
+@ARGV;" $*
Sorry, those long (wrapped) ugly pieces of code
are what's required
for MS Windows CMD shell. The command interpreter does not offer any means (that I
have discovered) of using continuing statements on multiple lines when defining a
DOSKEY macro. Don't try a COPY-PASTE of the above, either, or you'll have to
figure out how to remove every introduced newline inside the macro definition before
the code will work. Trust me, you won't feel good about the wasted time.
To use the above code, you must place it in a *.bat or *.cmd file
and then "execute" it from the MS Windows console (the commandline interface,
CLI, CMD.exe).
Invoke the macro (not the .bat file it was saved in, which you
execute only once per each shell session or instance) with a
single arg, the Perl-style name of a module (for ex. “pmtest CGI” or
“pmtest File::Find”).
Here's the Unix shell (bash/ksh etc.) rendition of the
pmtest thing
# pmtest: bash reusable function authored by Soren Andersen
# license/terms of use/modification/redist: same as Perl
pmtest ()
{
perl -e'
my$modn = my$mod = "'$1'";
$mod =~s@::@/@g; $mod.=q[.pm];
die ("module $modn not installed.\n",$@) if
! eval {require qq[$mod];};
my $modv = defined ${$modn.q[::VERSION]} ?
${$modn.q[::VERSION]} : q{[version undefined]};
my$numtyp= (2 > $modv =~tr/.//) ? "%s" : "% 6d";
printf " %-*s $numtyp in %s\n",
length($modn) > 30 ? 5+length($modn) : 15+length($modn),
$modn, $modv, $INC{$mod};
';
return 0
}
This also needs to be "gotten into" the bash session somehow. Ths canonical
way of doing so is to include the above in a shell initialization file
like ~/.profile or ~/.bashrc.
For contemplation by people who want to write software installers,
Perl installation administrators, etc.:
In contrast with Unix-like platforms, MS Windows has it's own sense of Well-known Folders
(not absolute filesystem "folders" but instead pointers to locations which can reasonably
be expected to exist on most
Windows machines, with some divergence between the bog-ordinary Workstation and the more
complex Server kind of Windows installation).
These are abstractions, meta-directories if you like, which exist above the
level of the actual filesystem and happen to be represented in the typical, default Windows ENV
by variables like %APPDATA% and %ProgramFiles% and %ALLUSERSPROFILE%.
We can access the values assigned to these meta-directories using the API calls
wrapped in the Win32.pm module (not in the core namespace which is automatically
built in when Perl is created for a Windows system; the user has to explicitly
say use Win32; in order to make this work).
Here's a simple one-liner to demonstrate:
perl -MWin32 -le 'my @ds=grep {/CSIDL_/} @{ [keys %Win32::] }; ' \
-e 'do {printf qq/%31s => %s\n/, $_, Win32::GetFolderPath(&{$Win32::
+{$_}}) }'\
-e 'for map { $_->[0] } sort {$a->[1] <=> $b->[1]} map { [$_,&{$Win3
+2::{$_}}] } @ds'
Note that we did not even need to know the particular names of the metadirectories
available on the specific version of Windows on which this is run, which is Kinda Cool
imho.
Here's a way to get the location of the meta-directory of your choice, assuming that you
choose with some clue to begin with ;-/ ... :
perl -MWin32 -le "my @ds=grep {/^CSIDL_/ && /\U$ARGV[0]/} @{ [keys %Wi
+n32::] };
do {printf qq/%31s => %s\n/, substr($_,6), Win32::GetFolderPath(&{$
+Win32::{$_}}) }
for @ds" profile
This should display the Special Folders that are named *PROFILE* (in globbing terms) and
display the actual location(s) of such folders.
Note also that the above commandlines aren't broken up in actual use, and will have to be mended
by any who wish to try it out. MS Windows CMD shell doesn't allow multi-line commands
even inside quotes UPDATE:
You can create multi-line
Perl one-liner (console input) scripts in the interactive Windows CMD shell. You will escape the newline with
the ^ character (caret) but this does not work to span lines inside quotes.
Instead, you will use -e repeatedly, just as you may do in a *nix sh-type shell. Here's the
oneline demo above, thanks to pKai who educated me on this!:
perl -MWin32 -e "my @ds=grep {/CSIDL_/} @{ [keys %Win32::] };" ^
-e "do {printf qq/%31s => %s\n/, substr($_=>6), Win32::GetFolderPath(&
+{$Win32::{$_}}) }" ^
-e "for map { $_->[0] } sort {$a->[1] <=> $b->[1]} map { [$_,&{$Win32:
+:{$_}}] } @ds"
Here's a DOSKEY macro-ized version of the code above. Handy for interactive CMD shell
use where you need to quickly check the list of Special Folders (or a particular group of them).
:: MS Windows BAT/CMD syntax. Wraps a Perl one-liner program.
DOSKEY SPECIALFOLDERS=perl -MWin32 -e "my @ds=grep {/CSIDL_/} @{ [key
+s %%Win32::] };
do {printf qq/%%24s=>%%s\n/, substr($_=>6), Win32::GetFolderPath( &
+{$Win32::{$_}} )}
for map { $_->[0] } grep {(0+@ARGV ? $_->[0]=~m<$ARGV[0]>i : 1)
+}
sort {$a->[1] <=> ${b}->[1]} map { [$_,&{$Win32::{$_}}]
+ } @ds" $*
Remember to reformat the code above so that no linebreaks are present. The line that begins
with DOSKEY needs to be one continuous line.
·For MSWin
-using Monks·
- You can emulate the Unix sh-shell user-defined function examples
shown on this node to some extent by using DOSKEY macros.
DOSKEY still exists on Windows XP, Vista, and 7. In a CMD shell you
can query what macros you've defined by doing
D:\ > DOSKEY /macros
and can define new macros by saying something like this:
D:\ > DOSKEY perlversion=perl -le "printf qq[%vd$/]=> $^V"
This is a somewhat trivial and quite contrived example of course. ;-)
Here's a less contrived example. This will make cli work easier if you
find yourself working in a directory named like C:\Documents and Settings\You There...
DOSKEY compactcwd=FOR /F "delims=*" %%N IN ("%CD%") DO CD %%~sN
There are some DOSKEY/Perl gotchas to look out for. Note that this is not an exhaustive list.
- The special tokens $* and $B, $G, $L and $T (case does not matter) will be interpreted by DOSKEY
instead of DWYM with Perl This means that scalar variables must not
be named $[Bb].* or $[Tt].*, using regexp
meta-syntax to explain. You could say ${Beginning} or
${tangent}, though.
- The % sigil in a hash variable name (or a printf format, or anywhere else) must be doubled if you
are trying to set up DOSKEY macro definitions in a batch
file script. The first one is "eaten". (Note: I've some reason
to think that escaping a % with a caret ^ might work, but I
haven't had time to test this. I think that in general, quoting with
the ^ in CMD doesn't work inside double quotes.)
- Batchfile as DOSKEY macro-file (thanks, Ben Burnett):
- The macros discussed above can be cleverly included in a CMD
session using this as a file (say, save it as PMACROS1.bat)
and starting CMD from a shortcut like this:
%SYSTEMROOT%\System32\CMD.exe /E:on /F:on /V:on /K CD %USERPROFILE% & PMACROS1.bat
;= @echo off
;= rem Call DOSKEY and use this file as the macrofile
;= %SystemRoot%\system32\DOSKEY /listsize=1024 /macrofile=%0%
;= rem In batch mode, jump to the end of the file
;= goto end
;= rem ***************************************************************
+***
;= rem * Filename: DOSKEY-M1.cmd
;= rem * Version: 2.0
;= rem * Author: Soren Andersen <somian08@gmail.com>
;= rem * Purpose: Some useful perl 1-liners
;= rem * license/terms of use/modification/redist: same as Perl
;= rem * Last modified: Wed 28 Dec 2011
;= rem * History:
;= rem ***************************************************************
+***
;= rem PMTEST: Test for use of a Perl module
PMTEST=perl -le "do{$modn=$_;s!::!/!g;$_.=q[.pm];do{print qq[$modn is
+not installed.];next} unless eval qq#require(\"$_\");1# && !$@;$modv=
+defined(${$modn.q[::VERSION]}) ? ${$modn.q[::VERSION]}:q{[version und
+efined]};$numtyp=2>$modv=~tr/.// ?'%s':'% 6d';printf qq[ %-*s $numty
+p in %s\n],(length>30 ? 5+length:15+length),$modn,$modv,$INC{$_}}for
+@ARGV;" $*
;= rem SPECIALFOLDERS: Display Well-Known Folder pathnames
SPECIALFOLDERS=perl -MWin32 -e "my @ds=grep {/CSIDL_/} @{ [keys %Win32
+::] }; do {printf qq/%24s=>%s\n/, substr($_=>6),Win32::GetFolderPath(
+&{$Win32::{$_}})} for map {$_->[0]} grep {(0+@ARGV ? $_->[0]=~m#$ARGV
+[0]#i : 1)} sort {$a->[1] <=> ${b}->[1]} map {[$_,&{$Win32::{$_}}]} @
+ds" $*
;= :end
Documentation for the current version of PPM (3),
the crufty thingy that many MSwin users rely on to install new packaged Perl modules:
ppm3 Documentation
|
- You can easily break your PPM v3 unknowingly merely by
updating Text::Autoformat – see
Bug Listing
|
- PPD file format – appears
to have not been updated since the 5.6 series releases at
ActiveState. Please note that it makes
no mention whatsoever of a parameter or field named
ARCHITECTURE NAME then go and in contrast
look at some example .PPD files from the various repositories.
Note Added:
This seems to be explained by
this brief excerpt
from the ppm Mailing List, authored by Jan Dubois:
"Since Perl 5.6 and Perl 5.8 are not binary compatible, we started appending
the Perl version number to the architecture string in ActivePerl 5.8. Try this:
<ARCHITECTURE NAME="MSWin32-x86-multi-thread-5.8" />
Both ppm2 and ppm3 in ActivePerl 8xx have been patched to use these architecture names."
|
- A (perhaps) little-known, rich PPM repository to add to your list that ppm searches.
|
- For Perl5.8 you may check status
of ActiveState's builds of packages (modules).
|
The dmake utility:
The recommended tool for building Perl from the source kit using a Free C/C++ compiler
(MinGW), is dmake. This variant of the classic make tool is now
maintained by OpenOffice.org folks ("tools" Project) and the dmake manpage is online.
dmake on CPAN: is now maintained by
Steve Hay and is no longer the extremely old code offered years ago by Gurusamy
Sarathy. Steve is building it using MSVC++ from the OO.org source mentioned above.
|
·For EveryMonk· (any platform)
Investigate the modules and libraries your Perl installation
has access to:
Tom Phoenix' script "Inside" on CPAN.
Need Help Using CPAN Effectively?
Preflight-check for CPAN.pm mirrors (using system `ping(1)'):
perl -MCPAN -l \
-e 'CPAN::Config->load;' \
-e '@pcnt= $^O eq "cygwin"? qw(-n 2):qw(-c 2);' \
-e ' do{ $fn=$_;
if (s#^\w+p://([^/]+).*#$1#) {
print $fn; system("ping",@pcnt,$_); print "\n","-"x52
} }
for @{ $CPAN::Config->{urllist} }'
# code tested on cygwin and GNU/Linux
Find your system's master list of CPAN mirror sites, maybe freshen it up:
perl -MFile::stat -MCPAN -MLWP::Simple=mirror -le 'CPAN::Config->load;
+ my $fhost;' \
-e 'my $Mdat = $CPAN::Config->{keep_source_where}.q[/MIRRORED.BY];'
+\
-e 'if (-e $Mdat and -M _ < 14) { print qq[$Mdat: freshness OK, last
+ modified: ]' \
-e ' .gmtime stat($Mdat)->mtime()' \
-e '} else { ($fhost)=grep(/^http/,@{$CPAN::Config->{urllist}});' \
-e 'die "no suitable cpan http mirror host" if !$fhost;' \
-e 'printf q[%s],qq[File $Mdat not found or stale, will d/l fresh fr
+om $fhost ...];' \
-e 'mirror($fhost .q[MIRRORED.BY] , $Mdat) and print q[ ].gmtime(sta
+t($Mdat)->mtime)}'
Wrap the code above in a function in your shell initfile if you are a bash
user and you like to have such conveniences at your "fingertips", as I do:
function mirrorsrefresh
{
< above perl code here >
}
More tips on coping with CPAN.pm can be found
here at "dumpcpanurls" Snippet.
Easy way to see that script output gets a terminating newline automatically:
In scripts:
#! /usr/bin/perl -l
# *or*
$\ = "\n"; # do it once and won't have to again.
In one-liners (script is "-e"):
$ perl [other flags] -le "[some code]"
Filter newlines out of systems call results
%hash = ( key => grep [ chomp ], `which ps` );
which does the same things as:
%hash = ( key => grep {chomp || 1} `which ps` );
Attribution: seen on comp.lang.perl.misc
in msgid <3F447BDB.9928761A@acm.org>.
Slurp an entire file in
# Previous declaration of "$filename" is assumed.
my $data = do{local(@ARGV,$/) = $filename;<>}
Attribution: here
Another way to do this, faster and better:
my $data = do{ open local(*FH),$filename or die "can't open: $!" ;
sysread( FH, my $buf, -s FH ) ; $buf ;
};
Something that may be called "The Bartian Transposition" someday:
(@a[0 .. ($#a = $#b)], @b) = @{[ @b, @a]} # swap two arrays
Where's my HOME???
my $home = $ENV{'HOME'} || $ENV{'LOGDIR'} ||
(getpwuid($<))[7] || die "WAAAAA! I'm HOMEless!\n";
# from `perldoc perlop'.
Something really special:
Opcode scanning for Safe.pm
Dump a string of opcode names that can be fed to Safe::new->permit. Based on knowledge / shell
elan shared by ysth.
$ perl -MO=Concise,-exec <FILENAME.pl> \
| perl -lnaF -e '$_=$F[2]; s/\W.*//; $h{$_}=0; END{ print join " "=>k
+eys %h}'
Created 30 Jul 2003 EDT (GMT+4):
Updated Thu Jul 31 2003
Updated Sun Jul 04 2004
Regarding the Meditation on List Cleanup
[After getting helpful advice on the node above I rewrote the snippet (as a complete scriptlet) ... several times (mostly recently on July 4 2004)]
The goal is to eliminate duplicates without disturbing existing
ordered-ness. Thus the property of mundane hash assignment such
that duplicates disappear is not sufficient by itself, but in a
combination demonstrated in this code below, the truth-ness of
a hash value can be used to prevent duplicate array entries.
#! /usr/bin/env perl
# "uniqnord" - remove dups from a list of identifiers.
use strict; use warnings;
$, = ! -t STDOUT ? "\n" : " " ;
my %seen = (); $\ = "\n";
print STDOUT join($, =>
grep {!$seen{$_}++} map {
if (/ +/) { $/=" " ; @_=split }
else { chomp ; $_ }} <>)
__END__
|
The real code:
#! /usr/bin/env perl
# "uniqnord" - remove dups from a list of identifiers.
use strict; use warnings;
$, = ! -t STDOUT ? "\n" : " " ;
my %seen = (); $\ = "\n";
print STDOUT join($, =>
grep {!$seen{$_}++} map {
if (/ +/) { $/=" " ; @_=split }
else { chomp ; $_ }} <>)
__END__
|
Posts by Intrepid
|
EU::MM, StrawberryPerl, Gnu make ...
in Meditations
3 direct replies — Read more / Contribute
|
by Intrepid
on Oct 26, 2008 at 16:31
|
|
I want it the way I want it.
I got around to trying my own suggestion for altering the
Config for StrawberryPerl in the manner I proposed,
in the discussion over here, recently. I had said:
So a superior approach might be to set cc in the Perl Config-heavy.pl
file to the fully-qualified pathname where the mingw gcc that's shipped with Strawberry
is installed. That way the right gcc is always called:
- Config_heavy.pl: cc='gcc'
- becomes: cc='C:/strawberry/c/bin/gcc'
Strawberry's setup program alters the MSWindows system PATH
(%Path%) env var but that's inherently fragile when something later
(like a brain-damaged user or other software setup program) could come along
and clobber that.
The results thus far have not been ok. The error seen pertains to how EU::MM is deciding
what the semantics for invoking the link step of extention library file creation ought to
be... see Link:
extracted snippet
from the Makefile generated by ExtUtils::MakeMaker on Strawberry, showing how it tells make to
direct the compilation of the extention lib (in this case, for the extension module List::MoreUtils).
Those familiar with the technicalities of the GNU ld linker and
how gcc syntax for its invocation works will recognize that -out:
and -def: are completely unGNUish and in fact are the parameter syntax for
the Microsoft linker.
This is drearily familiar because this is what using Perl the way I want to
on MS Windows has always been like. Things often "almost work" but not quite.
In this case what I believe is happening is that somewhere in the depths of the
MakeMaker apparatus, somebody coded a fragile, over-simplified test for the
Config value of cc; and if it is not just plain gcc in
Config, the apparatus decides that 'that other compiler' (Microsoft's cl.exe)
must be the one available. I am surely going to check that out and see if I'm right ...
Ok, checked, and it's the line in ExtUtils::MM_Win32 that does
my $GCC = $Config{'cc'} =~ /^gcc/i ? 1 : 0;
that is responsible for this badness. That was a piece of coding lacking in foresight
if ever I have seen one. How about a more reasonable, reliable, flexible
my $GCC = ($Config{'cc'} =~ /^gcc/i or $Config{'cc'} =~ /gcc(?:\.exe)?$/i) ? 1 : 0;
instead?
It is such a bummer that the way adding modules on MS Windows works, is based
on these contortions deemed necessary for the historical MS Studio tools etc, then
awkwardly twisted back to the GNU toolset provided by the MinGW project. MinGW
GCC + friends are basically the familiar *nix tools and work so very similarly, yet
where Perl is concerned MinGW's gcc is some half-known mystery that can barely be dealt with.
Apparently that's 'OK' because the main port of Perl to MS Windows is fashioned
in such a way as to build and interoperate mainly with the Microsoft proprietary
development system ;-/.
What I am truly wishing for is a way to override ExtUtils::MM_Unix code with
MinGW-compatible syntax only instead of going anywhere near that damn
ExtUtils::MM_Win32 module. ;-/
The other thing I am most wishing for from Strawberry and similar Win32 perls is that
the GNU make tool can be chosen to build CPAN modules, instead of the dmake program.
I know GNU make inside and out and use it for building all my other software. It's
apparently still a notion out there that "GNU make on Windows as MinGW provides it, isn't
working well enough to build Perl modules"; but MinGW's build of GNU make now reflects
steady improvement and is perfectly up to that task. And it's bundled as part of the MinGW
included in StrawberryPerl.
Node Updates |
27 Oct 2008 UTC |
Wanted to mention Link: ExtUtils::MM_Win32's
method for creating the link step make recipe (sub dynamic_link) …for deeper meditations. |
Two in the box, ready to go!
We be fast and they be slow! — GhostBusters II
|
UnBefuzzling XML::Parser: an adventure with EU::MM method overrides
in Meditations
3 direct replies — Read more / Contribute
|
by Intrepid
on Jan 16, 2008 at 06:29
|
|
First things first
The code is the major thing. The code is what the reader should try
running* and
try reading in order to understand the issues that I've addressed. The following
links are current as of Wed Jan 16 11:08:42 UTC 2008 and point to different kinds
of archives of the same source code kit, a tarball and a zipfile:
Please check the website
containing directory
first for more recent updates before downloading the files above, would be my advice.
* Try running $ perl Makefile.PL verbose — use the verbose flag.
Required Reading
The CPAN module Request Tracker (RT) ticket connected to this coding effort
is bug 32123.
Background on ExtUtils::MakeMaker
Documentation for the release of EUMM's MM_Unix.pm current as of this writing:
ExtUtils/MM_Unix.pm
In all that follows, EUMM (a.k.a EU::MM) is used as a widely-known
abbreviation for the ExtUtils::MakeMaker namespace and its sub-modules.
The notion at work in EUMM is code generation,
where the type of "code" being emitted is the declarative syntax understood by `make'.
The job of creating a Makefile was divided up into discreet methods, each of which would
be responsible for a single section of the final Makefile. When "overrides" are mentioned,
I am referring to the fact that about 60% of the methods for producing sections of Makefile
were designed to be "overridden" so that special-case platforms (like ms windows) could
be accommodated, or other special case scenarios could be achieved. The default methods
live, appropriately, in the namespace ExtUtils::MM_Unix; this could be seen as "appropriate"
since Unix is where Perl was born, and is such a (in many ways) standardized and
widely-deployed family of OSes (as the famous footnote in the Camel
puts it: "Assuming that you agree that Unix is both standard and fashionable" ;-).
In the ExtUtils/MM_Unix.pm module documentation mentioned above,
a symbol (o) next to the name of the method is used to indicate that the
method is one of the overridable ones. Methods lacking this mark do
not have the automatic support for overriding; they were assumed to be doing
parts of the Makefile text that would be invariant.
Future elaboration
There might be more discussion of this patch later. At the time that I started
writing this meditation I was not interested enough in teaching anyone anything
due to the fatigue I'm experiencing after combining the coding effort with the
effort to stay in touch with some of the other Perl authors involved. Such
efforts included trying to contact a certain person at a known hangout (#p5p at
irc - perl -org) and encountering the borderline psychosis so common among the
current set of p5p personalities ... so please vote according to your
displeasure at not finding more content here or at having the social club you
identify with being insulted (or at neither of the above).
Soren A / somian / perlspinr / Intrepid
--
Words can be slippery, so consider carefully who speaks as well as
what is said;
know as much as you can about the total context of the speaker's
participation in a forum over time, before deciding that you fully
comprehend the intention behind those words. If in doubt, ask
for clarification before you 'flame'.
|
rightway from US.pm
in Cool Uses for Perl
No replies — Read more | Post response
|
by Intrepid
on Oct 25, 2006 at 10:02
|
|
Let it be more convenient to use the 3rd-party unix-like sh shells with/from Win32-ish Perls.
This code is written as a module so that it is convenient to use from the command line. See
the SYNOPSIS section in the embedded POD, below.
package US;
use strict;
use warnings;
use vars qw($VERSION @ISA @EXPORT);
sub rightway;
$VERSION ='0.01';
use base 'Exporter';
@EXPORT = ('rightway');
=head1 NAME
US.pm - correct slash orientation in file path specs from native Win32
+ to Perl-canonical form.
=head1 VERSION
This documentation describes version B<0.01> of US.
=head1 SYNOPSIS
use US;
use Win32;
use File::Glob 'bsd_glob';
{
local $\ = "\n";
print for glob(
rightway Win32::GetShortPathName(Win32::GetFolderPath(Win32::
+CSIDL_COMMON_DOCUMENTS))
. "/*") ;
}
=head1 DESCRIPTION
Makes it more convenient to use the 3rd-party unix-like sh shells with
+/from Win32-ish Perls.
"US" as a name was not chosen with a nationalistic or xenophobic inten
+tion. The author
expects to use this code mainly from the commandline (in "1-liners" as
+ we say in Perl),
and as such a short, easy to remember name is a matter of convenience.
+ Ok? "U"=="Unix",
"S"=="Slash". Thus, "US.pm".
=cut
=head1 EXPORTED FUNCTIONS
=head2 rightway
=cut
sub rightway ($) {
my $pstr = shift @_;
$pstr=~ s{\\}{/}g;
$pstr;
}
1; # US like all modules, should return "TRUE".
__END__
=head1 AUTHOR, WARRANTY, COPYRIGHT, & LICENCE INFO
NO COPYRIGHT, NO WARRANTY, USE AT OWN RISK.
Created Oct 25 2006 by Soren Andersen. This code is considered by the
author to be so obvious and trivial that he hereby releases all claim
of rights to (and disclaims any responsibility for) the code, and
places it in the PUBLIC DOMAIN.
Last modified: 25 Oct 2006 at 09:31 AM EDT
=cut
|
METAreqWeb - overview of CPAN dist prerequisites
in Cool Uses for Perl
2 direct replies — Read more / Contribute
|
by Intrepid
on Oct 10, 2006 at 12:26
|
|
Solution to a chatterbox FAQ: what modules required are shipped with Perl? Which are already on the system?
This cli script sits at the corner of my desk awaiting the next
time I am looking up Perl modules at search.cpan.org.
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.
I context-click on the META.yml file and click "Copy Link Location"
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's prerequisites.
#!/usr/bin/env perl
# Last modified: 10 Oct 2006 at 12:02 PM EDT
# Author: Soren Andersen <intrepid -AT- perlmonk *dot* org>
# $Id$
use strict;
use warnings;
use YAML qw/ Load Dump LoadFile /;
use LWP::Simple;
use POSIX qw(isatty);
sub coremod { "" };
sub hr;
sub dimmer;
sub find_longest_keystring;
sub mtest;
sub testyml {
my $metayml_uri =
(shift(@_) || 'http://search.cpan.org/src/RUBYKAT/html2dbk-0.03/
+META.yml');
my $docu;
if( $docu = get $metayml_uri ) {
return $docu
}
die "Could not retrieve '$metayml_uri'. Network troubles? Bad URI?
+";
}
## And now a brief interlude of presentational trivia, not very intere
+sting
my $screenW = $ENV{COLUMNS} || 42;
my $unxterm = isatty(*STDOUT) && $^O !~/MSWin32/ ? 1 : 0;
if ($unxterm) {
require Term::ANSIColor and import Term::ANSIColor ('colored');
#print colored("Using Term::ANSIColor", 'dark white'), "\n";
} ## done with interlude, back to main show
my $metadoc = testyml (shift(@ARGV) || undef);
my $modmeta = Load( $metadoc );
if( $modmeta->{requires} ) {
my ($k,$v);
my $fmtlen;
my %reqrs = %{
my($mkl,@hash)
= find_longest_keystring($modmeta->{requires});
$fmtlen = $mkl || 28;
my $rh = {@hash};
};
if (eval "use Module::CoreList; 1" and not $@)
{
no warnings ('redefine','once');
sub coremod
{
my($pm) = @_;
my $presence_in_core = $Module::CoreList::version{$]}{$pm}
+;
return "\n" unless defined $presence_in_core;
my $pmv;
$pmv = $presence_in_core == 0 ? "without a VERSION number"
: "version $presence_in_core";
my $prn = Module::CoreList->first_release($pm);
my $note = <<" ELEPHANT";
CORE: $pm was first included in the core Perl distribution at Perl r
+elease $prn
The present Perl system shipped with $pm $pmv
ELEPHANT
return $note;
}
}
print hr;
printf <<" YODOWN"
%-${fmtlen}s %s
%s%s
YODOWN
=> ($k,($v eq '0'? 'any version':"at version $v") , mtest($k), coremo
+d($k))
while ($k,$v) = each %reqrs;
print hr;
} else # there are no prerequisite modules or pragmata listed
{ print "No requires for $modmeta->{name}\n"; }
sub mtest
{
my $installed_version;
my $wherep;
my $modname = shift();
my $modlibp = $modname;
$modlibp =~ s{ :: } {/}xg;
$modlibp .= '.pm';
my $can_req = eval "use $modname; 1;";
if ($can_req and not $@)
{
no strict 'refs';
$wherep = $INC{ $modlibp };
$installed_version = (${$modname.'::VERSION'}) || 0;
}
else
{
return colored(sprintf(
"%-32s is not installed"=> $modname) , 'cyan')
if ($unxterm);
return sprintf(
"%-32s is not installed"=> $modname)
}
if ($unxterm) {
colored(
sprintf('%-32s v%4s found as %s'
=> ($modname , $installed_version , $wherep))
, 'magenta' );
} else {
sprintf('%-32s v%-4s found as %s'
=> ($modname , $installed_version , $wherep))
}
}
sub find_longest_keystring
{
my %rethash = %{ shift() };
return () unless 1 * @{[ %rethash ]};
delete $rethash{'perl'};
my $l_maxed_at = 0;
for (keys(%rethash)) {
$l_maxed_at = length() > $l_maxed_at ? length() : $l_maxed_at
}
return ( $l_maxed_at, %rethash );
}
sub hr
{
my $decor = $unxterm
? dimmer("-" x $screenW)
: ("-" x $screenW);
$decor . "\n";
}
sub dimmer
{
colored( shift() , 'dark white' );
}
__END__
=head1 NAME
METAreqWeb
=head1 SYNOPSIS
./METAreqWeb [ <http://search.cpan.org/src/MOCONNOR/YAML-AppConfig-0
+.16/META.yml> ]
=cut
|
The Evil Embedded Space
in Meditations
6 direct replies — Read more / Contribute
|
by Intrepid
on May 30, 2005 at 02:53
|
|
This meditation mentions just a few thoughts about an aspect of using Perl on MSWin that has
been periodically coming up in discussions on the chatterbox. That aspect is the
presence or absence of embedded spaces in file pathnames. One can pretty much assume
that others will have differing opinions from what I present here, hopefully someone
will find it useful all in all.
|
fs branch point - common parent dir
in Cool Uses for Perl
2 direct replies — Read more / Contribute
|
by Intrepid
on May 14, 2005 at 20:39
|
|
When using certain common tools -- common to *nix-like OSes, anyway -- one
might sometimes like to have a way to find the "closest common containing
parent" of two directories. One example would be the invocation one makes
of the diff(1) tool. In Unified mode (diff switch -u) the
diff tool takes two directories and compares each file found in the first
with the same file found in the second (if it exists) (see the manual page
for diff for a better description of its operation).
Because the diff output contains "chunks" of data each lead by a pair of
lines that describe the "before" and "after" file locations, we could have
a very long line in either case if the path from the working directory
wherein diff was invoked is long. To improve readability / esthetics the
author prefers to keep these path specifying lines as short as possible.
The snippet presented here can be used as a shell script helper by substituting
its output into a cd (chdir) command so that the diff tool can be invoked
from a filesystem directory as close as possible to each target directory.
#!/usr/bin/env perl
eval 'exec /usr/bin/perl -S $0 ${1+"$@"}'
if 0; # not running under some shell
##--CVS/RCS control boilerplate--------
# $Author: SorenSpecial $ Last modified: 20:19(TZ:EDT) 14-May-2005
# Last cvs commit on: $Date: 2005/05/14 23:47:03 $
##-------------------------------------
use strict;
use vars '$DeBUG'; $DeBUG = 0;
use vars qw($VERSION $script_revision); # must be file-global non-lexi
+cals to be seen
# when using SelfLoader.
$script_revision = q$Revision: 1.3 $;
$VERSION = 0.03 ;
use Path::Class;
use Getopt::Long;
use Pod::Usage;
my( $help, $finemanualpage );
GetOptions('help|h|usage|u|?' => \$help, 'man' => \$finemanualpage)
or pod2usage(2);
pod2usage(1) if $help;
pod2usage(-exitstatus => 0, -verbose => 2)
if $finemanualpage;
pod2usage(1) if not $#ARGV >= 1;
my $root_token = File::Spec->rootdir;
sub togglroot {
if ( $_[0] =~ /\A[a-zA-Z]:/ ) {
return @_
}
return (substr( $_[0],0,1 ) eq $root_token)
? ( '', @_ ) : @_
}
sub find_common_parent_node {
my ($seen_comm, @dir1,@dir2, $dir_A,$dir_B, $cntup, $sharan);
my( $dir1 , $dir2 ) = @_;
$cntup =
scalar (@dir1 = ($dir1->volume(), $dir1->dir_list()))
<= scalar (@dir2 = ($dir2->volume(), $dir2->dir_list())) ?
scalar @dir1 : scalar @dir2;
while ( ++$seen_comm < $cntup ) {
$dir1[$seen_comm] eq $dir2[$seen_comm] ? next : --$seen_comm,last;
}
if ($DeBUG) {
printf STDERR qq:\n Dir1 has %u components\n %s\n
+ and seems to be %s:,
scalar @dir1, do { join qq[ ]=>map qq["$_"]=>@dir1 },
$dir1->is_absolute ? $dir1->stringify() :
File::Spec::Unix->rel2abs( File::Spec::Unix->catdir(grep
+$_,@dir1));
printf STDERR qq:\n Dir2 has %u components\n %s\
+n and seems to be %s:,
scalar @dir2, do { join qq[ ]=>map qq["$_"]=>@dir2 },
$dir2->is_absolute ? $dir2->stringify() :
File::Spec::Unix->rel2abs( File::Spec::Unix->catdir(
+grep $_,@dir2));
print STDERR qq:\n:;
}
if ($seen_comm) {
$sharan = dir(@dir1[0 .. $seen_comm]);
if ($DeBUG) { print STDERR "common ancestor is $sharan\n"
+ }
$dir_A = $dir1->relative( $sharan );
$dir_B = $dir2->relative( $sharan );
} else { $dir_A = $dir1 and $dir_B = $dir2 }
# print STDERR q[$dir_A is composed of elements ], map(qq["$_"],$dir_A
+->dir_list), qq[\n];
print STDERR "Comparing treelets rooted at [$sharan]:\n $dir_A\n
+ $dir_B\n" if $DeBUG;
return $sharan;
}
my ($dir1 ,
$dir2) = ( dir(togglroot shift @ARGV)->cleanup,
dir(togglroot shift @ARGV)->cleanup );
print find_common_parent_node($dir1,$dir2) .qq[\n];
__END__
Links provided for reader convenience:
|
MakeMaker-Makefile Reform School
in Cool Uses for Perl
3 direct replies — Read more / Contribute
|
by Intrepid
on Mar 30, 2005 at 17:38
|
|
Reforming the Makefile Madness for my specific machine / OS
NOTE: Updated Sat Apr 26 10:43:42 UTC 2008 to fix broken links pointed
out in child node 682635
make and Makefiles and all pertaining to that are so uncool that
for me they've wrapped right around back into cool.
Soren A / somian / perlspinr / Intrepid
--
Now, 2005: The 3 least meaningful terms in online jargon are:
troll flame rant
These used to mean something; but then they were highjacked by the kind of
inferior intellects who, when faced with a more erudite opponent employing
superior arguments (or simply hanging in there with a disagreeable
contention), abuse these terms as merely another form of name-calling. ;-)
|
OT: How to Spoil a nice place to live
in Meditations
8 direct replies — Read more / Contribute
|
by Intrepid
on Mar 03, 2005 at 11:15
|
|
Nothing at all to do with Perl... but something to do with Volunteering.
updated on Fri Mar 4 02:53:11 UTC 2005 -- a few changes of details (noted inline below)
I am so full of anger and frustration right now that has no outlet, so I decided that my daily cyberspace home was the only place where I could vent some of this in a way that felt at all meaningful.
The Story
The Cast of Characters: "A" and "B"
This is a story about two women and the society around them, and how one of them represents the kind that helps it all to hold together, and the other represents the kind that degrades it, generating the stress fractures that lead to massive failure, one little bit at a time.
Edit by castaway - closed some floating tags
|
Where do Perls come from, Mommy?
in Meditations
3 direct replies — Read more / Contribute
|
by Intrepid
on Apr 01, 2004 at 01:08
|
|
(as a personal policy I am going to be refraining from
replying directly to nodes posted Anonymously. It is so easy to set up a user
account on Perl Monks that I see little justification for anonymous postings here)
An Anonymous Monk wrote over there:
[...] (OSX Panther & Fedora Core 1) so I can't see how I have a non-
standard Perl on either of them.
Best regards.
|
Licensing Revisited ... again and again.
in Meditations
9 direct replies — Read more / Contribute
|
by Intrepid
on Feb 18, 2004 at 03:50
|
|
I was stimulated into re-visiting an issue that I've done a lot of thinking and reading about in
the past, by a conversation that erupted in the chatterbox today. It was initially a question
I put forth asking about people's past experiences with Sourceforge
which gave rise to this debate. The issue is software licenses, an issue which every hacker who
has been around for awhile thinks they understand very well, and most are eager to give
less well-acquainted colleagues the benefit of their insight ;-).
I won't refrain from mentioning that it was a specific Monk, my friend theorbtwo, who pointed
me towards the document that I'd like to discuss. I won't forbear to mention him since he is so
steadily a regular at Pm that he'll surely be around soon to make response to anything I write. ;-)
The document in question is the OSD, the Open-Source Definition. I hadn't taken much time reading the OSD until now; my time has been invested instead
in repeated careful study of the FSF/GNU GPL and related licenses, ones I was much more interested
in. Having read the OSD now, however, I came to a disturbing realization: the OSD is a mess.
|
|