Slash Boxes
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

sartak (7900)

  (email not shown publicly)

Journal of sartak (7900)

Tuesday April 21, 2009
07:24 PM


Tuesday April 14, 2009
07:28 PM

Warnings are good, damnit!

Warnings highlight possible bugs. The presence of a warning does not necessarily indicate a bug.

Only valid constructs will generate warnings! If a construct were invalid, then the system would have issued an error.

Warnings are not only for new learners. Warnings are also useful to experts, especially in the context of an evolving system. Delegating vigilance to the environment alleviates the burden of maintenance.

Changing code to cease its issuance of warnings usually requires disambiguation. This disambiguation is beneficial, because unambiguous code is clearer than ambiguous code. Encode your intent so that current collaborators and future maintainers will not have to guess at it.

If you truly require your code to run without warnings, then disable warnings entirely. The creation of warnings for potentially misleading or unexpected behavior should never require a battle. Existing code will not become incorrect, because warnings are not errors. However, you should still strive to correct the problems that issue warnings in new and maintained code.

edit: Some have missed the point of this post. I am not saying that having your code spew warnings is good in itself. I'm saying that having some warnings to alert you to suspicious code and to guide your fixes is what is good.

Wednesday March 25, 2009
09:52 PM

Breaking Sys::Protect

Sys::Protect does not bill itself as unbreakable protection, but it's fun to break it anyway.

PadWalker is used as an example of an XS module that could seriously mess with other code.

#!/usr/bin/env perl
no strict;
use warnings;
use Sys::Protect;
use Test::More tests => 1;

XSLoader::load(bless {}, 'Break::Sys::Protect');

my $password = 'c53eb8f992b4fdf70a03a4d437820028';
is(${PadWalker::closed_over(sub { $password })->{'$password'}}, $password);

package Break::Sys::Protect;
use overload q{""} => sub {
    return "Math::BigInt::FastCalc"
        if caller eq 'Sys::Protect';

    $_[0] = "PadWalker";

Don't use Sys::Protect. :)

Saturday January 17, 2009
03:21 PM


Jonathon Worthington just wrote about Perl 6's new support for parametric roles. Excellent!

Moose supports this feature too, through the MooseX-Role-Parameterized extension I wrote a little over a month ago. It has proved to be a very useful pattern. I'm pleased that Perl 6 has it built in.

Out of curiosity, I ported the examples Jonathon provided to MXRP. I'll have to work more with rafl to make MooseX-Declare support something resembling Perl 6's much nicer syntax. We do plan on having syntax for positional parameters in much the same way Perl 6's parametric roles do.

package Greet;
use MooseX::Role::Parameterized;

parameter greeting => (
    is       => 'ro',
    isa      => 'Str',
    required => 1,

role {
    my $p = shift;
    my $greeting = $p->greeting;

    method greet => sub {
        print "$greeting!\n";

package EnglishMan;
use Moose;
with Greet => { greeting => "Hello" };

package Slovak;
use Moose;
with Greet => { greeting => "Ahoj" };

package Lolcat;
use Moose;
with Greet => { greeting => "OH HAI" };

EnglishMan->new->greet; # Hello!
Slovak->new->greet; # Ahoj!
Lolcat->new->greet; # OH HAI!

I'll skip the second example because it's contained by the third example.

Moose doesn't give you multiple dispatch. sigh! Instead we model the problem with a default value for the transform, which is a code reference. In this way we meet the original requirement of EnglishMan and Lolcat not needing to provide a nominative->accusative transform.

package Request;
use MooseX::Role::Parameterized;

parameter statement => (
    is       => 'ro',
    isa      => 'Str',
    required => 1,

parameter transform => (
    is      => 'ro',
    isa     => 'CodeRef',
    default => sub {
        sub { $_[0] }, # identity function

role {
    my $p = shift;
    my $statement = $p->statement;
    my $transform = $p->transform;

    method request => sub {
        my ($self, $object) = @_;
        print "$statement " . $transform->($object) . "?\n";

package Language::Slovak;
sub accusative {
    my $nom = shift;
    (my $acc = $nom) =~ s/a$/u/;
    return $acc;

package EnglishMan;
use Moose;
with Request => { statement => "Please can I have a" };

package Slovak;
use Moose;
with Request => {
    statement => "Prosim si",
    transform => \&Language::Slovak::accusative,

package Lolcat;
use Moose;
with Request => { statement => "I CAN HAZ" };

EnglishMan->new->request("yorkshire pudding");
Lolcat->new->request("CHEEZEBURG ER");

I have no conclusion, except that Perl 5 hasn't been stagnant, though its new features can be a lot more verbose than in Perl 6.

Friday September 21, 2007
08:20 PM

Devel::REPL: now with multiline support

I've been using Devel::REPL for a while now. Like all good modules (Perl::Critic, POE, Plagger, etc), it's very extensible. Devel::REPL's design is worth studying: keep a simple core and ship all the fancy behavior as plugins. Moose amplifies the power and convenience of this design with roles, method modifiers, and general awesomeness.

There are plugins to dump output with Data::Dump::Streamer, enable tab completion of the current lexical environment and loaded modules, save input history across sessions, and more. However, if you dabble in other P-languages such as Python and Ruby (know thy enemy.. honest!) you'll find yourself wanting more out of Devel::REPL. Let's take the example of writing a factorial function in python:

% python
Python 2.3.5 (#1, Dec  7 2006, 14:50:51)
[GCC 4.0.1 (Apple Computer, Inc. build 5363) (+4864187)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def fact(n):
...     if n < 2:
...         return 1
...     return n * fact(n - 1)
>>> fact(10)

in irb:

% irb
irb(main):001:0> def fact(n)
irb(main):002:1> if n < 2
irb(main):003:2> 1
irb(main):004:2> else
irb(main):005:2* n * fact(n-1)
irb(main):006:2> end
irb(main):007:1> end
=> nil
irb(main):008:0> fact 10
=> 3628800

in lua:

% lua
Lua 5.1.2  Copyright (C) 1994-2007, PUC-Rio
> function fact(n)
>> if n < 2 then
>> return 1
>> else
>> return n * fact(n-1)
>> end
>> end
> =fact(10)

and in Devel::REPL:

$ sub fact {
Compile error: Missing right curly or square bracket at (eval 60) line
8, at end of line
syntax error at (eval 60) line 8, at EOF

D'oh. OK, let's try again..

$ sub fact { my $n = shift; return 1 if $n < 2; $n * fact($n - 1) }

$ fact 10

Well, that works in this case, but one big line of code quickly becomes unmanageable.

Recently I had the idea to use PPI to figure out if the current line of code is complete. PPI::Dumper quickly confirmed that I can detect the most important case: a PPI::Structure that doesn't have both a ->start and ->finish. Structures encompass { {nested { blocks } } }, (parentheses), [array indexing], {hash indexing}, and so on. Hopefully future versions of PPI will be able to figure out that, say, an s/// or quoted string is incomplete.

Here's what the factorial example looks like with the MultiLine::PPI plugin.

$ load_plugin 'MultiLine::PPI'
$ sub fact {
> my $n = shift;
> return 1 if $n < 2;
> $n * fact($n - 1);
> }

$ fact 10

I believe Devel::REPL is the only Perl REPL that can do this. Hooray! :)

You can change the default prompts with my FancyPrompt plugin. Here's how I actually have my prompt (code is slightly different to show off nesting). It may look like "ugh", but it's actually really nice when you're in the driver's seat.

> sub fact {
>> my $n = shift;
>> if ($n < 2) {
>>> return 1;
>>> }
>> else {
>>> return $n * fact($n-1);
>>> }
>> }

> fact 10

MultiLine::PPI hasn't been CPANed yet, but you can get it (and other new plugins) from the Devel::REPL Subversion repository.

I'll continue stealing good features from other REPLs. :)