|
User since: |
Jun 24, 2000 at 20:36 UTC
(24 years ago) |
Last here: |
Dec 12, 2024 at 02:55 UTC
(2 days ago) |
Experience: |
2672
|
Level: | Deacon (12) |
Writeups: |
224
|
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: |
Dec 13, 2024 at 19:39 EST
|
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:
sh-prompt $ perl -MText::Wrap='wrap,$columns' \
-MText::Textile=textile \
-lp000we \
'INIT{$columns=78} s{\cM?\cJ} [ ]g;
$_=wrap(q[],q[ ],textile($_)).$\;' DRAFT.TMP
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::] };
do {printf qq/%31s => %s\n/, $_, Win32::GetFolderPath(&{$Win32::{
+$_}}) }
for map { $_->[0] } sort {$a->[1] <=> $b->[1]} map { [$_,&{$Win
+32::{$_}}] } @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
|
Temp directories and the surprise creation thereof
in Meditations
1 direct reply — Read more / Contribute
|
by Intrepid
on Dec 04, 2024 at 23:09
|
|
Greetings from chilly, snowy Buffalo (NY, USA). I spent about 6 years doing no programming at all and now I'm using perl again. I am still hooked on it. So this week I started exploring CPAN modules that give info about and, in some cases, modify, the filesystem. I know of 3 modules that are used for that: the core module File::Spec, the module Path::Class (used it and liked it, a while back), and the module Path::Tiny. This meditation focuses on Path::Tiny, which seems to be stalking me. I see a lot of module authors using it in their code (that is, it has become a common dependency).
Path::Tiny is probably a bit of a misnomer. It has many methods. Many many. What I was most interested in this week was the method tempdir. Something about how tempdir works took me by surprise (yes, I am finally getting around to the point of this meditation :). The method returns a {normalized, right-slashed, absolute} pathname, but it also creates the temporary directory. Maybe I am odd, but I expected to be given a string and then create the directory with that pathname myself!
Below, some code (playful deliberately) that uses tempdir and will demonstrate that when tempdir is called, a directory is created.
#!/usr/bin/env perl
# Last modified: Wed Dec 04 2024 10:48:30 PM -05:00 [EST]
use strict;
use v5.18;
use utf8;
use warnings;
=head1 NAME
pathology.pl
=cut
use Term::ReadKey qw/ReadMode ReadKey/;
use File::Spec;
use Path::Tiny;
my $user;
sub versions
{
say
$File::Spec::VERSION, q[ ]
, $Path::Tiny::VERSION ;
}
sub who
{
no warnings 'deprecated', 'experimental';
use Config;
given (lc( $Config{osname} )) {
when ('linux') { $user = $ENV{USER} }
when ('cygwin') { $user = $ENV{USER} }
when ('mswin32') { $user = $ENV{USERNAME} }
default { say "osname is something we don't know, "
+,
"we'll guess it's something Unixy, so
+" ,
"let's say that user name is " ,
getlogin || "null";
$user = getlogin;
}
}
return $user;
}
# ------------------------------------------------------------- #
# For all its wealth of methods, I found no direct equivalent of
# "tmpdir" in Path::Tiny, so I use File::Spec's.
say "We use " , File::Spec->tmpdir , " for temporary files.";
# ------------------------------------------------------------- #
say "We are currently in directory " , Path::Tiny->cwd;
say "Our filesystem is rooted at " , Path::Tiny->rootdir;
say "Aha, " , who() , ", we may have a temp dir for you!";
my $tadah = Path::Tiny->tempdir(TEMPLATE => "${user}-XXXXXXXX");
say "Maybe we have made a temp directory at " , $tadah , ", let's see:
+";
if ( -e $tadah and -d $tadah ) {
say "'$tadah' already exists and is a directory.";
say "Type 'y' if you wish to remove this directory:";
ReadMode 'cbreak';
my $reply = ReadKey(0);
ReadMode 'normal';
if (lc $reply eq "y") {
print "Ok, we are going to attempt to remove it now ..." ;
rmdir($tadah) and say "Success."
or say "BAH! Could not remove it, reason: $!";
} else {
say "Ok, leaving $tadah alone.";
}
} else {
mkdir($tadah => 0777) and say "created temp dir."
or die "We couldn't make a directory \"$tad
+ah\"", $!;
sleep 6;
rmdir($tadah) and say "$tadah removed."
}
Dec 05, 2024 at 04:07 UTC
Examine what is said, not who speaks.
Love the truth but pardon error.
Silence betokens consent.
In the absence of evidence, opinion is indistinguishable from prejudice.
|
What's happening with the Cygwin project?
in Meditations
4 direct replies — Read more / Contribute
|
by Intrepid
on Oct 22, 2024 at 14:25
|
|
What's happening with the Cygwin project?
I recall recently seeing a remark (on a node I cannot find now) wherein the monk asked "is Cygwin still supported?" That's a good question. Certainly cygwinPerl seem to be alive and current on the Cygwin download servers (at the time of this writing, v5.40.0). But a mechanism for asking questions about Cygwin in general is seemingly problematic and has been for a while. The Cygwin website is completely out of date, directing users to mailing lists that do not exist anymore. Apparently to reach Cygwin developers one must use NNTP (we're talking old school here).
The Cygwin.com site says: "Please note that the gmane website and its newsgroup search interface is down since August 2016. Only the aforementioned NNTP gateway is still up."
I see a fair amount of traffic in Cygwin questions on StackOverflow and its related sites, and if someone were to ask me where to get general help with Cygwin today, that's where I would direct them.
Oct 22, 2024 at 18:07 UTC
Examine what is said, not who speaks.
Love the truth but pardon error.
Silence betokens consent.
In the absence of evidence, opinion is indistinguishable from prejudice.
|
Dei ex machina - State of the External Dependency Arts
in Meditations
1 direct reply — Read more / Contribute
|
by Intrepid
on Mar 23, 2013 at 06:08
|
|
Three past Perlmonks discussions in particular sparked this writeup.
- 1020332 Updating Config.pm late Feb 2013.
- 1020022 Installing Glib on Debian - same author as above, late Feb 2013.
- 1023945 this top post, and specifically that offshoot
comment.
The last thread above describes scenarios that involve difficulties encountered in
creating a correct installation of a CPAN module because of unfulfilled external
dependencies (where “external” in this context means provisioned from outside
the CPAN installer universe). The first two threads are perlquestions
involving a specific example of this kind of struggle. Read on to see where we
find ourselves once we enter this wilderness.
|
OO, from a blank file: an old perler dog tries new tricks
in Meditations
No replies — Read more | Post response
|
by Intrepid
on Feb 20, 2013 at 22:31
|
|
I am going to try something new here. I need to write an app in Perl to parse the output of
Cygwin's CygCheck.exe utility. I say "parse" as a shorthand for "read, munge, output" ;-)
What is new is that I am going to try writing the spec for the app as a Meditation on PMo
first before I start the app. Well, I know me, so I am already lying. I'll
start to write the spec here, and then start the coding. Then return to this writeup.
"Huh? Why?"
Just to do something fresh, to break some habits. I am not looking for upvotes or for a way to
promote my app (although I do intend to publish it; there will be a link in the post sooner or later).
The habits I want to break involve the organic way my coding usually proceeds. I start out with an
idea, code the skeleton, look for what breaks, decide to add some features, code, repeat, lather,
rinse, repeat. It's fine, its what I enjoy. It's also not as disciplined as other approaches, leads to
featuritis, and so on.
(As per the top heading), I think the best way is to start with a Perl-OO approach from the
beginning. That is really the realization that prompted this idea to write a Meditation. The
realization is that these days, I really have no idea where to start with writing Perl-OO code. There
are so many Perl-OO memes out there. There are so many helper modules on CPAN that template-ize or
automate the creation of objects. Damian's book is considered a good primer, but out of date.
<hands pulling out hair>. So where to begin?
I'm not going to wait for advice before I make some decisions and plunge in. For a PMo newbie that
would be fine, perhaps, although I do think that a lot of our newer posters don't show that they
get that they need to post code from the top of their Question ...but that's neither here nor
overthere.
Event-driven
I know that I want to treat my input as a sequence of events. Roughly, the input data is a series
of sections that describe system configuration and status data for the Cygwin installation. I will run
the CygCheck.exe tool with the flags -v -s -h -r to get verbosity, helpful hints, and Registry
queries.
The shape of the input data
A first glance at the input we expect breaks down like this (note: to an extent this is misleading
and contrived, because the CygCheck utility outputs some data that is not for public publishing).
Cygwin Configuration Diagnostics
Path: D:\UserSW\root\bin
Output from D:\UserSW\root\bin\id.exe
Here's some environment variables that may affect cygwin:
Here's the rest of your environment variables:
Scanning registry for keys with 'Cygwin' in them...
Cygwin installations found in the registry:
Listing available drives...
Mount entries: these map POSIX directories to your NT drives.
Looking to see where common programs can be found, if at all...
Looking for various Cygwin DLLs... (-v gives version info)
Checking for any Cygwin services...
Cygwin Package Information
Sweet, Eh?!
This gives a Perler a true-life opportunity to test themselves against some perversely difficult
input. These "headings" are highly irregular (arbitrary) in format; it may be that Localization will
affect this output (I have no idea), etc.
Preliminary Spec
What will be "success":
- The “section events” will all be detected;
- All data within each section can be manipulated (filtered, reformatted);
- Any section can be removed from the output;
- No “unhandled” text data will be lost after the input stream is terminated.
Design:
- Each section will be represented in code as an object with attributes (properties, methods).
- There will be at least 2 "dump" or "stringification" methods common to all instance/objects: plain text and YAML.
- There will be a "filter" method for each instance/object that will receive a coderef as @_[1].
- Each instance/object will know where in the input stream its instantiating triggering event
occured.
- There will be a common / consistent “placeholder” string representation for elided data.
And there we have it. Time to start coding ;-)
"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
|
Distro Pkg-Managed, broken Install.pm, sudo clears $PERL5LIB
in Meditations
2 direct replies — Read more / Contribute
|
by Intrepid
on Sep 27, 2010 at 14:02
|
|
Seeing error mentioned with (ExtUtils::MakeMaker) ExtUtils::Install (.pm)
I noticed that this recent Perlmonks node
says in part:
I use Ubuntu and typing # cpan WWW::Mechanize
produced the following […]
Not a HASH reference at [some path in standard system]/ExtUtils/Install.pm line 557.
I think I know how come that happens.
By the way, now that I've shown my solution to get a make install to work, let
me add for those with a different focus, that I don't hold the analytical opinion that I
or someone else on PMo has yet shown that there is a bug in the older ExtUtils::Install
module (version 1.44 on my local system). What can be deduced more plausibly is only that
using a newer revision of other ExtUtils:: library code as part of CPAN package
installing, is creating calls in Makefile "code" (target-building recipes) that may be
syntactically broken for the older Install.pm subroutine. In other words, backward-compatibility was broken.
|
pull a CPAN+ conf item
in Meditations
No replies — Read more | Post response
|
by Intrepid
on Apr 05, 2010 at 13:17
|
|
Another incomprehensible node from me
The trouble with using a nice tool like CPANPLUS for installing
Perl software from CPAN is that sometimes you can't ;-)
Relying on whatever one did when setting up CPANPLUS the first
time, one easily forgets what the conf settings were and just
lets the cpanp command do its thing. That's just what
it is for, and that's great.
But then one stumbles into a project like Image Magick
(imagemagick) with the PerlMagick component, which
is built “in-tree” when compiling the C/C++ main portion
of the project. Building from source for experimentation with a
pull of the latest
devel branch, say, or for any other of many good reasons that one
could have. What was once a convenience—CPANPLUS taking care
of 'remembering' your installFOO dirs, forexample—now
becomes an obstacle. You can fool around for many minutes figuring
out what on-disk location(s) CPANPLUS stores its configuration in,
or you can use this odd little technique we like to call
programming to aquire this information with far
less irritation and effort.
All that it takes is addition of something like this snippet to
a Makefile (it will be a generated Makefile in cases where the
the GNU Autotools or similar are employed), before running the
make command in the cli/console.
Disclaimer: use at your own risk. No guarantee of efficacy or
protection from hair loss is made or implied.
The following snippet is also an example of one way
(Intrepid's way) of “embedding”small
Perl programs in a Makefile. It is not the only
possible way. And it relies on this Makefile
being a GNU makefile, that is, the make
tool being used to interpret and execute the Makefile
must be GNU make. See further notes below.
For those who were not paying attention:
This is make "code", not Perl
except for the part in between the define
and endef.
# ...
## ----------------------------------------------------- ##
# discover where we want to install Perl interface modules
# that come bundled with this package / src kit (as with
# the imagemagick software)
## ----------------------------------------------------- ##
P_INSTALL_CONF = UNDEFINED
.PHONY : pmdest
sinclude cpanp.mk
define Perl1
use CPANPLUS::Backend;
my $gregory = CPANPLUS::Backend->new;
my $corso = $gregory->configure_object;
for ($corso->options( type => q/conf/ )) {
/makemakerflags/ && print $corso->get_conf(q|makemakerflags|);}
endef
cpanp.mk : pmdest
@echo >$@ "P_INSTALL_CONF := $(strip $(shell cat $<))"
pmdest:
@perl -le '$(strip $(value Perl1))' >$@
_debug1: cpanp.mk
@cat $<
# ...
build-pm: pmdest build-stamp
@echo $(if $(filter $(P_INSTALL_CONF), UNDEFINED, $(error WE HAVE
+NO VALID DEF for P_INSTALL_CONF), Perl build starting ...))
cd $(CURDIR)/PerlMagick && perl Makefile.PL $(P_INSTALL_CONF)
# ...
This works nicely because the GNU-make define FOOBAR
directive used
above creates a quantum of data that isn't evaluated as a Make
directive / statement at the time of declaration. That is,
the sigils ($) in the Perl code are not
“dereferenced” or “evaluated” as
make variables at the time that make reads in the statement,
as it makes a parsing pass through the Makefile.
By later using the $(value <...>) function to
protect the sigil-strings (Perl scalars variables) from
premature molestation by make (so that they are passed
through unaltered to the system command interpreter (sh)
and
thus to perl), we manage to take our precious
bits of enlightened Perl wisdom like the perl code above,
and get it delivered to perl for execution.
The use of little files written to disk in the build tree, by make,
in the process of acquiring this data for build configuration, is
a necessary evil, it seems. RFF! (Request For Feedback).
The Perl code is shown in isolation here:
use CPANPLUS::Backend;
my $gregory = CPANPLUS::Backend->new;
my $corso = $gregory->configure_object;
for ($corso->options( type => q/conf/ )) {
/makemakerflags/ && print $corso->get_conf(q|makemakerflags|)
}
Whether you found this edifying or irritating, next time you hear that someone cannot
figure out how to extract some conf settings from the inner sanctum
of a utility like CPANPLUS, remember to advise them
(please don't “advice” them)
that CPANPLUS
comes with documentation that describes an API for doing exactly that.
[Intrepid|Soren Andersen /
“somian” / “perlspinr”]
|
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'.
|
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.
|
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
|
|
|
|