Dei ex machina - State of the External Dependency Arts
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.
|
Does Perl Have a Business Plan?
7 direct replies — Read more / Contribute
|
by punch_card_don
on Mar 21, 2013 at 22:50
|
|
|
Monetary Monks,
Being just a lowly programmer, uninvolved in the bigger picture, I barely dare stick my nose in this. But the recent spate of community introspection about Perl's future did make me, in my ignorance, wonder: Does Perl have a business plan?
Such a question may be obscene to some people. But, just like any for-profit business, a lot of people have a lot invested in the Perl product. Even a peon like myself - it would be far preferable for me personally if the many hours invested in developing even my humble level of Perl proficiency (rather than some other potential money-earning knowledge) produced a decent ROI. Far preferable to having it not. I'm sorry if that's not a pure enough motivation, but the kids want food and shelter and iPads and high speed internet so they can watch Indie musicians being broke purists. In the context of the macroeconoimic theory of happiness and light, whether Perl does well in the marketplace of programming options or not doesn't amount to a hill of beans. But in the context of the opportunity cost to those individuals who have invested irreplacable time betting on Perl as one of the languages of their repertoire ('cause few of us are genius enough to learn everything) to earn a living, it matters a great deal.
Perl will produce an ROI for those investors if there is sufficient demand for Perl's product that Perl programming service providers are in demand.
For that to happen, requires all the ingredients of any decent business plan.
First, the product, Perl, must meet the market's needs better than its competitors. The best way to ensure that is real market research, investigating what the businesses that use programming want programs to be able to do, then resource identification and allocation for product development that directly addresses that research.
But the business world is littered with good offerings that still failed to win the market. Even a good product needs a marketing plan as part of the overall business plan. Few people on the production floor fully appreciate the invaluable job the marketing and sales departments do in a company. Without promotion, the best product in the world will go unnoticed, and everyone on the line is out of a job. Every successful product has a sales and marketing machine behind it.
So - for those of us who know nothing about the Perl hierarchy - does Perl have a business plan?
Time flies like an arrow. Fruit flies like a banana.
|
Old Monks go gentle into that good night.
5 direct replies — Read more / Contribute
|
by punch_card_don
on Mar 21, 2013 at 09:22
|
|
|
Maturational Monks,
Dawdling about the Monastery over morning coffee, I wandered into the Saints in our Book node. And was intrigued by the entries in the "Last Here" column that are measured in years: 3 years ago, 4 years ago, 5, 6, 7... 8 years ago!
In other words, people who have moved on to other things.
Now, people move on in their work lives. But what struck me was the casualness of the breaks. Look at these people's most recent posts. In almost all cases, their last post was some ordinary act of replying to a node. One minute they're engaged Perl users, hanging out on PerlMonks answering questions. Then, perhaps the very next minute after that last post, their work lives take some sort of turn that expunges Perl discussion from their lives forever. Or at least for 3,4,5...8 years.
Perl monks, it seems, by and large, don't go out with a bang - they just go gentle into that good night. One minute a Perl Monk brimming with years of knowledge and skill, the next minute there will never be cause for another conversation about Perl for the rest of their lives. No fanfare, no decision - just silence.
I find it ponderous. Years spent honing a craft, amassing knowledge. It's all so critically important in the moment. Then one day, it's not. It all just becomes irrelevant enough to never speak of it again. I think it would be a very interesting study to know what happened in all these people's lives at that point.
But this most certainly has zero to do with Perl and everything to do with life. A case of Perl-life illuminating a facet of life in general. How many things do we experience in the same way. There's not always a graduation, or a divorce, or a retirement party, at the end of a phase in life.
Sometimes, we just move on.
But in the meantime, the thing that so obsessed us for so long has served us well. Its new irrelevance does not diminish the reality of its importance to us at the time. Nor does our moving on diminish the real value of whatever it is to those who are entering a similar phase of life. So hopefully all that knowledge and experience don't get truly lost. Hopefully it gets passed on to those who are now finding it critical to their lives.
In the context of Perl, and programming in general, this brings us full circle to PerlMonks.org. Old monks can go gently into that good night without the the accompanying tragedy of all that knowledge being lost. So all is right and good in the universe.
Time flies like an arrow. Fruit flies like a banana.
|
For thought: "Perl in the greater context of (me and) the software business
7 direct replies — Read more / Contribute
|
by sundialsvc4
on Mar 19, 2013 at 16:59
|
|
|
In polite response to the recent spat of posts here, I would like to offer a perspective ... my perspective, but also a perspective of thirty-plus years ... on “Perl and the software business.”
First of all ... “my business,” for many years now, “is not ‘Perl.’” Or perhaps ... it’s certainly not just Perl. I will hazard to suggest that this is undoubtedly true of most, if not all, of the “old hands” here. We have clients (or employers), who not only depend on us to work our magic, but who entrust their deepest businesses with us. Perl is just part of that magic.
My actual job, at this point, is actually that of a software engineer. “You, mister customer,” are “somewhere,” and you have concluded (at this point, rightly or wrongly) that “you are not in the place where you today wish to be.” And my job is to figure out (a) how to stabilize “where you are now” (if you are in imminent danger of plunging into some abyss), and (b) to plot a course .. and a project plan, and a budget, etc. .. to wherever it is I recommend that you should now go.
“Engineering.”
Along the way, I will as-needed engage the über-specialists (if any) that may be required to get you there. I will, unbeknownst to you, arrange with each and every one of them to do their respective specialist part. Nothing special here: general-contractors hire subcontractors all the time.
It is actually typical that any project will involve multiple language systems, even on the server side. All of them, each in their own quirky way, has their own way to get you “there.” You, the client, got “there” by some pathway that today we cannot change. My job is only secondarily to consider where “there” is. My primary job is to discern where “there” should be. From this, the language-specific voodoo consists of a fairly sensible number of good choices. There are many languages to choose from, but also strong incentives to “dance with the one that brung ‘ya.”
And I honestly believe that, in saying all of these things, I probably speak for most of the “old hands” here, as well as many others. If the choices that we had to make were simple, bright-line choices ... why would anyone seek us out? (Hint: they wait in line.)
So, perhaps this will at least help to explain why I look at “this language vs. that one” arguments with a very puzzled eye. Software systems are built using languages, and, having been thus constructed, never depart from them; nor should they. Code that provably works is, indeed, a priceless thing. Most systems involve multiple languages as well as considerable history ... and yet, they provably work (okay, okay, “more or less”).
That is, at least IMHO, the computer software business. Perl, like all the others, is merely a means to an end ... a tool ... and a worthy tool it is. (Perl does not stand alone, but it does stand proud.) If you regard Perl, or any other language, “as an end unto itself” in this business, I submit that you are ... and I do not mean this “personally” ... missing the point, entirely. So much that I once again regard you, “with a very puzzled eye.” Perl is not the point. My clients, and what they wish to accomplish, are. Perl, along with all the others, is merely how I/we get there. The client does not care: the client pays us so that they don’t have to care.
i
|
How to wake up the Perl community?
8 direct replies — Read more / Contribute
|
by PetaMem
on Mar 19, 2013 at 09:45
|
|
|
Seriously. How?
One can try it with humour (or so): http://www.youtube.com/watch?v=UJ1hkwfC7G0
or with arguing and arguing and arguing - only to see that most of the undoubtedly brilliant and intelligent Perl guys have a total blind spot when it comes to thinking outside of the technical domain.
You can try it with shock therapy in the hope some of the totally blind (and deaf) will awaken. Your success rate will be far from 100% however, because you underestimate the "blindness" and thinking in the box. Or - as I heard recently - being in the "echo chamber".
You will hear FUD - just the inverse way. Like "Python users are so asocial, they do not even manage to have workshops." ... or "TIOBE is flawed". YES! IT IS! But the bright guys who completely clearly brightly intelligently and logically explain to you why it is flawed, completely totally and ultimately tragically fail to see the point that "TIOBE is relevant". If someone dares to challenge me on that point, I will gladly accept.
You can try to throw in more facts to wake some people up and show them that their language is perishing and why that is so and - more important - what can be done about it. Google trends for Perl and e.g. Python, other "popularity indices" (no you will not find Perl in there), module count, number of job postings, number of books sold/written/available. But even that will awaken 1-2% at most. The rest is pretty ok with sleeping or simply does not care.
Then you can create a Propaganda.pm group and gather some people who've already awakened around you. Will that be enough to awaken everyone else? Most certainly no.
You can fight "wars" in other areas that are the tipping points. And ask the Perl community for help. In their own best interest. Will they listen? Will they wake up? You should not bet on it.
You can rant about the situation
I just found out, that the Perl community is a bunch of lethargic
old-farts who deserve no better than "their language" to persish. ...
Hmm. No that would not make a good motivational entry. I will have to
reformulate this in a more euphemistic fashion while keeping the
meaning untouched.
and get an equally perfect motivational bounceback:
Welcome to the world of the real ;-)
unfortunately I've had that opinion for a while, and it's very hard
to get anyone to do anything seriously positive, in part because of
all the brown-nosing in the [despite anonymous quote this has to be
censored]... People like Gabor (and you) still try to make a
difference, but it's like pushing water uphill.
You should never awake sleeping dragons - they say. I really would
like this dragon to be awakened, but am afraid, that it's just a wall
lizard. But I'll keep on making noise. We'll see if I get spit fire
upon or eaten or if the dragon agrees to go out for a ride.
Anyone any other idea? More meditation is needed.
|
RFC: Algorithm::Damm
2 direct replies — Read more / Contribute
|
by MidLifeXis
on Mar 17, 2013 at 09:36
|
|
|
I have written my first module for community consumption, and am looking for comments:
I am pulling comments into git issues, so if you want to save the middleman (or provide a pull request), feel free.
|
Threads and signals in Windows
4 direct replies — Read more / Contribute
|
by bojinlund
on Mar 08, 2013 at 04:39
|
|
|
Hej!
The purpose of this post is to make me and hopefully also other to understand more about the handling of signal in Windows. Knowledge about signals in Windows is essential, if you want to implement a portable module which uses signals.
I have several times been “hit” by signals in Windows, mainly as a user of modules. I have also tried to understand how signals can be used in Windows. In the Perl documentation I have only found some sentences about it. If you are a UNIX/Linux user and want to write portable code, you get probably very little help from the documentation. Without clear statements of what is wrong it is also difficult to send bug reports.
Super Search gives a lot of information about the topic, but often in specific situation. The results from Super Search show that this is a difficult area. It also show that there is a lot of knowledge in the Monastery.
Some of the background to my proposals and questions are at the end of the post.
What could be done?
Here follows a list of things that could be done to improve portability of modules, in particular from UNIX to Windows. Some of them are perhaps not realistic but can anyway trigger other ideas.
Discourage use of signals
State that: “If you want to write cross-platform code, you shouldn't use signals, full stop.”
Perlwin32 in the Perl documentation says:
“Using signals under this port should currently be considered unsupported.” If this still applies, this information should also be placed so module developer using other operating system is aware of it and do not use signals in modules intended to be portable.
Depreciate signals between threads in Windows
Eventually make it impossible from Perl to use signals between threads in Windows.
If you use signal in a wrong way there is a risk to also disturb thing outside the Perl program.
Using signal in an inappropriate way can result in a stochastic behaviour of Perl programs.
Discourage use of fork
Make people aware of the big difference between fork in UNIX and Windows.
In many cases will the differences result in portability problems.
To support the moved from fork, there should be examples showing how to, in a portable way, solve function typically solved by using fork.
Depreciate fork in Windows
Phase out fork in Windows.
New pragma use portable
Introduce a pragma which issues a warning when non portable functions are used.
Use Perl::Critic to enforce portability
Use the Perl::Critic extensible framework to enforce coding guidelines for portability.
It can also be used to indicate “dangerous” functions and constructs.
Questions
Portable alternatives
Is threads a portable alternative to fork?
Is there any portable and feasible ITC alternative to signals in Windows?
Documentation of signals in Windows
In “win32/win32.c” there is a mapping between signals and Windows events.
You can also read things like “the child may be blocked in a system call and never receive the signal”.
Where can I find information about this in the documentation of Perl?
Background
TerminateThread is a dangerous function
In the win32 implementation of Perl, ”kill -9 style un-graceful exit” is using ”TerminateThread”.
The “Remarks” in the documention of TerminateThread contains:
TerminateThread is used to cause a thread to exit. When this occurs, the target thread has no chance to execute any user-mode code. DLLs attached to the thread are not notified that the thread is terminating. The system frees the thread's initial stack.
...
TerminateThread is a dangerous function that should only be used in the most extreme cases. You should call TerminateThread only if you know exactly what the target thread is doing, and you control all of the code that the target thread could possibly be running at the time of the termination. For example, TerminateThread can result in the following problems:
- If the target thread owns a critical section, the critical section will not be released.
- If the target thread is allocating memory from the heap, the heap lock will not be released.
- If the target thread is executing certain kernel32 calls when it is terminated, the kernel32 state for the thread's process could be inconsistent.
- If the target thread is manipulating the global state of a shared DLL, the state of the DLL could be destroyed, affecting other users of the DLL.
Threads and processes should terminate themselves
Re: Proposal how to make modules using fork more portable
IPC and ITC are different but mixed up
The common fork model is to create a (child) process and the communication between parent and child is Inter Process Communication (IPC).
However in Windows fork creates a (child) thread within the process.
The communication between parent and child in Windows is an Inter Thread Communication (ITC).
The separation between processes are different than that between threads. Threads are typically sharing more things than processes.
An ITC signal in Windows do not interrupt a blocked I/O operation.
“Signals and Windows: Very limited emulation by Perl. Not reliable.”
“Signals and threads: They are not a useful mechanism of Inter-Thread Communications.”
Stochastic behaviour of Perl program in Windows
Using signal in an inappropriate way can result in a stochastic behaviour of Perl programs.
I have seen cases when this not just influence the Perl program, but also other processes in the Windows system. In some cases it is even not possible to switch off the system in the normal way.
I would hesitate to use a program with a stochastic behaviour in a production system.
Another consequences of the "none-deterministic" behaviour is that the module tests should be run several times.
Best Regards
Bo Johansson
|
Installing Template::Toolkit on Windows
4 direct replies — Read more / Contribute
|
by davies
on Feb 22, 2013 at 08:44
|
|
|
This is needed by BugZilla and, I believe, other applications. Unfortunately, I've never been able to install it without a fight, one of which I documented in PPM has module but BugZilla says it's missing, and the goalposts seem to me to be highly mobile. I'm writing this in the hope that it will help people who are in the same position as I am and inspire those with the knowledge, power and tuits to make life a little easier for us lesser mortals. If you already know all these things, I will be wasting your time, but I had to do a lot of studying to work them out for myself. This is the short version.
The BugZilla installation instructions at https://wiki.mozilla.org/Bugzilla:Win32Install make the process look easy. The only route suggested is the command line as follows:
C:\>ppm install Template-Toolkit
Downloading Template-Toolkit-2.22...done
Unpacking Template-Toolkit-2.22...done
Generating HTML for Template-Toolkit-2.22...done
Updating files in site area...done
140 files installed
What could possibly go wrong? Well, it appears that ActiveState no longer serves TT, at least for 64 bit 5.16.2. At this point, I went off on a useless search. Google made it appear that there would be something useful at http://www.template-toolkit.org/. From here I went to the downloads page (http://www.template-toolkit.org/download/index.html) which talks about BugZilla. The links to ppm packages seemed to be exactly what I wanted. At this stage I was getting really optimistic, until I clicked on the link for the ppm download for TT. If you want to see a 404 error, this is the place to go (http://landfill.bugzilla.org/ppm/Template-Toolkit.ppd). As I said, the goalposts do seem to move, so I entertain hopes that this may change to something other than a dead end.
The next thing I tried was CPAN. While I was ultimately successful, I approached it with great trepidation. My only previous attempt (documented at Raspberry Pi: some sort of dependency hell involving YAML) had not been a success, and the helpful advice to use something else still rang in my ears. I didn't think that AS would have written ppm if CPAN worked better all along. It didn't start well, either. It tried to install "dmake" and the MinGW c compiler (which I thought I had installed anyway with git) and failed. The process threatened "This may take a few minutes", but I have a fast, powerful computer that was running nothing else, as well as a fast internet link, so it only took about 20 minutes. Anyway, I have no idea whether these things are necessary nor, in the case of "dmake", what its purpose is, so I decided to keep trying.
CPAN's help (brought up by "h"), is more of the form of a memory jogger than something to get the beginner started. It assumes rather a lot of knowledge, especially about things like "make". I believe that dmake and nmake (of which more later) are Windows variants of make, but if someone corrects me they are more likely to be right than I am. But it suggests install so, following ppm, I tried install Template-Toolkit. This complained about being unable to find the package, but suggested using i. This returns a list of possibilities, but there is little or nothing to indicate what to do next. I don't know if it is what I want, but the incantation that seemed to give me progress was install ABW/Template-Toolkit-2.24.tar.gz.
The process started with the reporting of so many files that I couldn't scroll back to the start as the buffer (set to the maximum Windows will allow) wasn't large enough. It then complained about the lack of a c compiler and make utility and started - apparently - the same process that had taken 20 minutes to fail earlier. Another 20 minutes later, I was pleasantly surprised to see a report of success. I was also told Please use the `dmake` program to run commands from a Makefile! without any clue as to where to find dmake, what a makefile is or why I might want to run commands from one.
I then got a lot of text about Template::Stash::XS, followed by a pair of options where I used the defaults:
Do you want to build the XS Stash module? [y] y
Do you want to use the XS Stash by default? [y] y
I suspect that these should not be chosen unless a c compiler is available, but as indicated earlier, I'm not absolutely sure what constitutes "available". Anyway, this produced some encouraging messages until a range of colours that I won't attempt to reproduce reported (I've tried to improve the wrapping):
Configuration complete. You should now run 'C:\Perl\site\bin\dmake.ex
+e', 'C:\Perl\site\bin\dmake.exe test'
and then 'C:\Perl\site\bin\dmake.exe install'. See the README file f
+or further information.
'nmake' is not recognized as an internal or external command, operable
+ program or batch file.
ABW/Template-Toolkit-2.24.tar.gz
nmake -- NOT OK
Running make test
Can't test without successful make
Running make install
Make had returned bad status, install seems impossible
Failed during this command:
ABW/Template-Toolkit-2.24.tar.gz : make NO
First, the "dmake" commands have to be run in a way I didn't expect which I will explain in the next paragraph. Second, "the README" file is either missing or lost among all the others that exist on my machine. Third, the mention of "nmake" seems to be a total red herring. These can prove a vast time sink and certainly got me nowhere. I made further progress only when I gave up and tried to install again from scratch.
This failed with the message Has already been unwrapped into directory C:\Perl\cpan\build\Template-Toolkit-2.24-RFIUGI. However, this gives an important clue. Leaving the CPAN shell, I changed to this directory and then tried issuing the three "dmake" commands suggested earlier.
Bugzilla's checksetup routine now indicates that TT is present. Only 9 more modules to go.
Regards,
John Davies
|
Perl is my cast iron pan
7 direct replies — Read more / Contribute
|
by talexb
on Feb 21, 2013 at 23:34
|
|
|
I cooked some seasoned chicken breasts tonight for supper using my cast iron pan. First I turned the oven up to 300F (still old units for some things, even in a country that's been metric for about 30 years), then I put the cast iron pan on medium heat and let it warm.
Once the pan was ready, with the oven still heating, I seared the chicken two minutes per side, keeping a lid on the pan, then popped it into the oven, and started cooking rice and beans on the stove.
The chicken was ready when the rice was, about half an hour later, and I was pleased to see that it had stayed nice and moist. The meal was delicious.
Four hours after having cooked supper, I went back to the pan and washed it. Now, you never use soap on a cast iron pan -- that's a no-no -- because cast iron is slightly porous. It retains a little fat, and naturally provides a non-stick surface (or, mostly non-stick, anyways). Clean-up is a little scrub with my metal Kurly Kate and some water, then a bit of a dry with a cloth. I re-season this pan once in a while, but after 25 years use, it doesn't need it much. It's a well-used, well-loved pan, and one of my favourites.
Sort of like how Perl's been my favourite for some time -- about 15 years ago I was starting to tinker around with scripting languages because I was getting tired of writing C programs to open files, read arguments from the command line, do the usual munging of data. I found Perl after a little noodling with awk. Perl does have its quirks, both in the language and in the community. But treat both right, and you'll be well served for years and years.
So when I see some commercial on TV for a new kitchen appliance (and some of the American commercials are most comical, as seen by these Canadian eyes), I smile, just as it amuses me to read SlashDot's talk about how use in Perl is declining.
No, it's not the latest, coolest, shiniest thing, but there are many smart, hard-working people on the job behind Perl (the language and the community). And like my cast iron pan, it's going to be around, useful as ever, for a long time to come.
Alex / talexb / Toronto
"Groklaw is the open-source mentality applied to legal research" ~ Linus Torvalds
|
OO, from a blank file: an old perler dog tries new tricks
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
|
"undef" is not NULL and what to do about it
9 direct replies — Read more / Contribute
|
by Ovid
on Feb 20, 2013 at 11:31
|
|
|
What's wrong with undef?
Currently undef has three different coercions: false, zero, or the empty
string. Sometimes those are correct, but not always. Further, by design, it
doesn't always emit warnings:
$ perl -Mstrict -Mwarnings -E 'my $foo; say ++$foo'
1
$ perl -Mstrict -Mwarnings -E 'my $foo; say $foo + 1'
Use of uninitialized value $foo in addition (+) at -e line 1.
1
And because it has no precise definition, undef might mean any of a number
of things:
- The value's not applicable
- It's not known
- It's not available
- It's restricted
- Something else?
In other words, the behavior of undef is overloaded, its meaning is
ambiguous and you are not guaranteed to have warnings if you use it
incorrectly.
Now think about SQL's NULL value. It's problematic, but no alternative has taken hold for simple reason: its meaning is clear and its behavior is unambiguous. It states quite clearly that 'if I don't have a value, I will treat that value as "unknown" via a set of well-defined rules'.
So, between the ambiguity of Perl's "undef" and the clarity of SQL's NULL, it's probably not surprising that some code could use the latter instead of the former. In fact, I will go further as to assert that the code is often clearer if you do that. Case in point:
foreach my $employee (@employees) {
if ( $employee->salary < $threshold ) {
increase_salary( $employee, 3_000 );
}
}
I'm sure plenty of you see the bug: what if the employee doesn't have a salary? I've already outlined several reasons above for why the salary might be undefined, not all of which mean "this employee has no salary". So if salary is undefined, you will probably get a warning and you'll have a bug. If threshold is undefined you'll get a warning but you won't have a bug. Fun, eh? So you might rewrite the code like this:
if ( defined $threshold ) {
foreach my $employee (@employees) {
my $salary = $employee->salary;
next unless defined $salary;
if ( $salary < $threshold ) {
increase_salary( $employee, 3_000 );
}
}
}
Now that's starting to get ugly. Wouldn't it be if we had simple, clear NULL semantics instead? Now you can, with Unknown::Variables. I explain this idea at length at blogs.perl.org, but it works like this: instead of using "undef", you use "unknown".
use Unknown::Variables;
my $value = unknown;
my @array = ( 1, 2, 3, $value, 4, 5 );
my @less = grep { $_ < 4 } @array; # assigns (1,2,3)
my @greater = grep { $_ > 3 } @array; # assigns (4,5)
There's a lot more to this module than meets the eye, but the idea is that the unknown keyword (well, it acts like a keyword), unlike undef, has clear, well-defined semantics and and predictable behavior.
In the employee salary example above, if an unknown salary returns unknown instead of undef, our code goes back to the original:
foreach my $employee (@employees) {
if ( $employee->salary < $threshold ) {
increase_salary( $employee, 3_000 );
}
}
Further, you won't generate any warnings because warnings are there to warn you when you're doing something bad. In this case, unknown values are designed to be compared an behave appropriately. And as you can see, our code above becomes much simpler. When used appropriately, unknown values can let your code focus on the problem rather than work around fiddly bits of the language. Any place that you find yourself assigning undef in your code, see what would happen if you put an unknown value there instead.
Feedback welcome. Download the code from the CPAN or, if you want to hack on the code, clone it on github.
|
getting rid of costly special features
7 direct replies — Read more / Contribute
|
by LanX
on Feb 17, 2013 at 08:07
|
|
|
DB<108> $str='zy'; print $str++," ",$str++," ",$str++
zy zz aaa
except maybe in one liners???
I'm sure when Perl was intended to replace sed and awk this was super cool, but now it's just weird too special to be worth the trouble.
What are the chances that one day we have a pragma unfeature which disables such stuff?
|
Perl mailing list activity
4 direct replies — Read more / Contribute
|
by Steve_BZ
on Feb 14, 2013 at 17:34
|
|
|
Hi Guys,
I was just looking at the Perl mailing list activity statistics: http://www.nntp.perl.org/group/, and I'm looking at the graph on the right.
It seems to me that that usage between Jan 2003 and April 2010 was relatively stable. Maybe there was some overall decline in activity, but not greatly. Up to April 2002 there was clearly a lot of momentum and since April 2010 there has been a noticeable and accelerated decline in activity.
What happened in 2002 and 2010 to cause theses changes of trend line?
I guess I feel a little disappointed to see usage of my favourite language falling off like this.
Regards
Steve
|
A strange old perl bug: "Can't use an undefined value as an ARRAY reference" error given for a misleading/wrong line number
2 direct replies — Read more / Contribute
|
by elumelum
on Feb 12, 2013 at 20:05
|
|
|
#!/usr/bin/perl
use strict;
my $undef_ref = undef;
my $array_ref = [1,2,3];
if (!scalar @{$array_ref}) {
print "foo\n";
}
elsif (!scalar @{$undef_ref}) {
print "bar\n";
}
Running this code under perl v5.8.8 gives me:
Can't use an undefined value as an ARRAY reference at arrayref2.pl line 8.
...which is the check on the defined array reference.
Running this code under perl v5.10.1 (*) (with 59 registered patches), the next newest perl I had available, produces this output:
Can't use an undefined value as an ARRAY reference at arrayref2.pl line 11.
...which is the check on the undefined array reference.
When laid out this way, I think most would agree that it is easily identifyable as an issue in perl v5.8.8.
However, when I ran across this while working on some legacy perl code at my job (hence the old version(s)) and this situation was masked by much more complex conditionals that were much more deeply nested, this was a real pain to figure out! I was especially thrown off at first when I changed the equivalent of the first if to:
if (0) {}
...and it still gave the same undefined array reference error for that line! Though that is also part of what led me to discovering the issue ultimately.
I was unable to turn up anything quite like it searching the web, as for obvious reasons, most of the results were dealing with situations in which the line number reported actually contained an undefined variable being used as an array reference.
I thought I would write this up here on the off-chance that it might turn up amongst search results for someone else if they run into this same issue.
|
Untillian Headache or about the semantic of until
5 direct replies — Read more / Contribute
|
by Discipulus
on Feb 11, 2013 at 08:50
|
|
|
hello there,
I want share an headache with you due to the Perl's loop control until structure.
I'm currently happily reading, with some profit i hope, High Order Perl and so far, apart from some math base i do not have, i can quite afford it. and i very like it.
While explaining iterators apllied to permutations the author, with the usual kindness, come back a little to present a simpler problem: an odometer.
Realized that the odometer is that set of little wheels showing how many kilometers my kawasaki GPZ 750 divoured in his history, i looked at the subroutine proposed with a "ah ok... is very simple. i can get it.." approach.
This line, clear in the result wanted, mazed and puzzled me:
until ($odometer[$wheel] < 9 || $wheel < 0)
This is the original code of the sub with a little prepended code just to call it, putted by me.
use strict;
use warnings;
my @odometer = qw(0 0);
for (1..$ARGV[0]) {
print "was: @odometer\t";
@odometer = increment_odometer(@odometer);
@odometer ? (print join ' ', @odometer) : (print "No more Wheels t
+o turn! $!" and exit) ;
print "\n";
}
sub increment_odometer {
my @odometer = @_;
my $wheel = $#odometer; # start at rightmost wheel
until ($odometer[$wheel] < 9 || $wheel < 0)
{
$odometer[$wheel] = 0;
$wheel--; # next wheel to the left
}
if ($wheel < 0) {
return; # fell off the left end; no more sequences
} else {
$odometer[$wheel]++; # this wheel now turns one no
+tch
return @odometer;
}
}
The semantic translated
Now come in count another think, i'm not eng-native (as my name suggest i speak latin..).
Every word in english have an attached logical translation in my mind and, while i read some perl code, this is used as logical unit to build up the scenario: i cannot think in english..
I know that until simply invert the condition of the same while loop.
The 'while' in my native language is 'mentre' and the reverse 'until' is 'finché'. But while the first transaltion fit well in any circumstance, the second does not apart from trivial case of the condition.
I took the english-italian dictionary and i found that until is translated as 'finché (non)'. This beacuse in english until want a positive sentence but in italian 'finché' bring the possibility to use a negative form of the sentence after it, and in this way is commonly used: 'i wait until you arrive' can be translated as 'aspetto finché arrivi' but also sounds good as 'aspetto finché NON arrivi'.
In italian the double negation is admitted and correct: 'Non c'è nessuno' is 'There is nobody' but have a double negation ('non' and 'nessuno') but sound as 'there is not nobody'.
Inverting the condition
Naturally the original code is correct (this was never in doubt) but now i want a valid logical representation of it in my mind so i played with the line with the until condition:
until ($odometer[$wheel] < 9 || $wheel < 0) #ok original
#negated direct form also ok
while ( !($odometer[$wheel] < 9 || $wheel < 0) )
while ($odometer[$wheel] > 9 || $wheel < 0) # NO
while ($odometer[$wheel] > 8 || $wheel < 0) # OK but NOT for greter th
+an limit of the odometer!
#Use of uninitialized value in numeric eq (==) at C:\SCRIPTS
+\odometer.pl line 27.
#Modification of non-creatable array value attempted, subscr
+ipt -3 at C:\SCRIPTS\odometer.pl line 26.
#getting: 9 9->
while ($odometer[$wheel] == 9 || $wheel < 0) # OK but NOT for greter
+than limit of the odometer!
#Use of uninitialized value in numeric eq (==) at C:\SCRIPTS
+\odometer.pl line 27.
#Modification of non-creatable array value attempted, subscr
+ipt -3 at C:\SCRIPTS\odometer.pl line 26.
#getting: 9 9->
while ($odometer[$wheel] == 9 && $wheel >= 0) # OK
It does not appear the first attempt using an 'LABEL if redo' solution because i think i'm too young to use LABELs.
But really the negation of ($odometer[$wheel] < 9 || $wheel < 0) is ($odometer[$wheel] == 9 && $wheel >= 0) ?
This is not a critic to Perl or about the choice of words in the language or a request to abolish the poor until is only something i want to share about the problematic enlace between a logical language and a spooken one.
L*
there are no rules, there are no thumbs..
Reinvent the wheel. Then learn The Wheel and use it!
|
|