Skip to content

each @array in Perl 5.12

June 6, 2010
tags:

Don’t recall seeing anyone blog about it and in fact the documentation is pretty sparse but from Perl 5.12 each can now iterate over an array like so:

use 5.012;
use warnings;

my @array = 'a' .. 'h';

while (my ($i, $val) = each @array) {
    say "$i => $val";
}

each on an array returns two values… the index and the value of the current iteration. Thus we get this output from above code:

  0 => a
  1 => b
  2 => c
  3 => d
  4 => e
  5 => f
  6 => g
  7 => h

Anyway to save me thinking up a blog post please excuse me while I just regurgitate my Stackoverflow answer I gave earlier today about using each with an array:

==start==
Starting with Perl 5.12, each is now more flexible by also working on arrays:

use 5.012;
use warnings;

my @tokens = 'a' .. 'z';

while (my ($i, $val) = each @tokens) {
    if ($val =~ m/[aeiou]/) {
        ($i, $val) = each @tokens;   # get next token after a vowel
        print $val;
    }
}

# => bfjpv

One caveat with each, remember the iterator is global and is not reset if you break out of a loop.

For eg:

while (my ($i, $val) = each @tokens) {
    print $val;
    last if $i == 12;
}

# => abcdefghijklm

my ($i, $val) = each @tokens;
say "Now at => $val ($i)";         # Now at => n (13)

So use keys or values to manually reset the iterator:

keys @tokens;                      # resets iterator
($i, $val) = each @tokens;
say "Now at => $val ($i)";         # Now at => a (0)

==end==

I’ve just come back from a nice weeks break… so I’m still a lazy git in holiday mode here :)

/I3az/

Where did it go?

May 27, 2010
tags: ,

My last post a couple of days ago, What I Would Like To See, seemed to have hit the Ironman bitbucket :(

There is no mention of Perl in the article (a first for me for probably over a year!). But it is tagged with “perl” and “ironman”. Is there an issue with WordPress tags? Is ironman only seeing WordPress categories (which were “blogging” and “programming” for this post).

Thought I better check what my WordPress RSS feed is spewing out using XML::Feed:

use 5.012;
use warnings;
use XML::Feed;

my $feed = XML::Feed->parse(URI->new('http://transfixedbutnotdead.com/feed'))
    or die XML::Feed->errstr;

for my $entry ($feed->entries) {
    say $entry->title;
    for my $category ($entry->category) {
        say "\t", $category;
    }
}

What came back was this:

	What I Would Like To See
		Blogging
		Programming
		perl
		ironman
	Perl block with lexically-scoped method delegation
		Programming
		perl
		Devel::Declare
		dsl
	PDL advert get its 15 minutes of fame!
		Programming
		PDL
		perl
		stackoverflow
	Perlcast website is back
		Blogging
		Programming
		perl
		perlcast
	Podcasts & Perl
		Programming
		perl
		podcast
	Famous Perl programmers
		Programming
		perl
		python
		django
	Caralyst 5.8: The Perl MVC Framework
		Programming
		catalyst
		perl
	Perl ads on Stackoverflow
		Programming
		perl
		stackoverflow
	Two questions… similar answers… same module
		Programming
		moose
		perl
	The unlikely intersection of Boy George and Damian Conway
		Programming
		london.pm
		perl

Both the WordPress tags & categories were coming through has RSS categories. I believe this is correct so why hasn’t Ironman picked up the “What I Would Like To See” post?

So is having Perl, CPAN or ironman in the content mandatory?

/I3az/

What I Would Like To See

May 25, 2010
tags: ,

I think I would love to see mst present a YAPC talk on Catalyst, Rails & Django – the shootout!

No web framework is perfect so I think it maybe insightful to highlight the best & worst features of all these frameworks and see how they stack up against each other.

And to provide complete impartiality for the talk then I think the hair colour should be a mixture of green for django, red for rails and eh, not sure what colour for catalyst?… so lets stick to mst’s natural hair colour for that :)

/I3az/

PS. BTW… if you think my multi-colour choice was a bit OTT, then its fortunate I didn’t go with my original thought of suggesting using the colours of my favourite Rugby & Footie teams! That would have been eye catching mix of black & gold for London Wasps and the blue & white Superhoops :)

Perl block with lexically-scoped method delegation

May 15, 2010

About a year ago I came across this interesting Ruby blog post Keyword With.

This is something I always wanted in Perl and immediately marked a note in my list of blog/CPAN ideas with “Devel::Declare and with statement” (with side note that “using” might be more appropriate so not to clash with Moose roles sugar).

Unsurprisingly this just languished in my ever increasing list :(

However last month I had a few hours spare one weekend so pulled out my laptop and rummaged through my list and decided to see how difficult it would be to implement “with”.

Unfortunately I kept hitting brick walls with local scoping. I came to conclusion that I may have to use eval or even go down a different track using an AUTOLOAD solution.

I left that weekend experiment with at least a very basic AUTOLOAD proof of concept:

use 5.012;
use warnings;

{
    package FileStuff;
    use Moose;
    
    has name => ( is => 'rw', isa => 'Str' );
    
    sub save { say "save ",   $_[0]->name }
    
    sub del  { say "delete ", $_[0]->name }
    
    sub mv {
        my ($self, $to) = @_;
        say "rename ", $self->name, " to $to";
        $self->name( $to );
    }
    
    sub say { say "Method say: ", @_ }
}

my $f = FileStuff->new( name => 'foobar' );

# using $f {}
{
    local *AUTOLOAD = sub {
        our $AUTOLOAD;
        my $name = (split '::', $AUTOLOAD)[-1];
        die "method $name NOT FOUND!" unless $f->can( $name );
        $f->$name( @_ );
    };
    
    # my "DSL" stuff!
    save();               # $f->save();
    mv( "barbaz" );       # $f->mv( "barbaz" );
    del();                # parenthesis are always required
    say( "builtin say" ); # builtin wins over $f->say
}

I wasn’t sure if this would ever evolve into a robust solution. However I found it reassuring to note that other people had similar problems trying to use local scoping in similar way when I came across this Perlmonks post A useful use of goto a few days later. So this gave the AUTOLOAD approach some merit.

Well chances are this blog post or any additional development may never made it any further. What changed that was an email from chocolateboy this morning pointing me at his new Scope::With CPAN module.

Blimey… Father Christmas had delivered my xmas pressie early and without even seeing my xmas list :)

chocolateboy’s first example of Scope::With even shows how it works with my Builder module:

use Builder;
use Scope::With;

my $builder = Builder->new();
my $xml = $builder->block('Builder::XML');

with ($xml) {
    body(
        div(
            span({ id => 1 }, 'one'),
            span({ id => 2 }, 'two'),
        )
    );
}

say $builder->render();

Which is exactly why I wanted a “with” statement in Perl and it looked like chocolateboy also felt the same!

The documentation even gave an “using” example:

use Scope::With qw(using);

using ($xml) {
    div(
        span( ... ),
        span( ... ),
    );
}

Getting worried now someone was reading my mind :)

This is truly awesome stuff. chocolateboy has the habit of producing game changing CPAN modules. For eg. autobox and Method::Lexical. To me Scope::With is potentially another one that falls into this lofty category.

I’m deeply honoured to find my Builder module being referenced and also glad to see that a “with” statement using Devel::Declare and AUTOLOAD isn’t such a delusional idea :)

So many thanks to chocolateboy for writing Scope::With. Keep up the good work.

/I3az/

PS. chocolateboy’s Scope::With docs also references a prior art module with by Vincent Pit. This module achieves similar things but in different way/implementation.

PPS. CPAN is so big and wonderful that its easy to miss or even forget whats on there!

PDL advert get its 15 minutes of fame!

May 6, 2010

You may recall that I added the PDL (Perl Data Language) logo to Stackoverflow opensource ads recently.

Well the logo achieved its 15 minutes of glory when it was fortuitously screen captured for the following ReadWriteWeb article about Stackoverflow raising venture capital:

Well done to all those of you voted this up to make this happen :)

NB. This is the Hacker News post which pointed me to the ReadWriteWeb article.

/I3az/

Perlcast website is back

May 4, 2010
tags: ,

Good news, Perlcast is back from the GoDaddy grave :)

Bad news, The Perl Report which I list on my blog links as now disappeared :(

Fingers crossed The Perl Report is only a temporary issue. And touch wood Perlcast can return to more regular podcasts (perhaps its something that TPF can look into has part of their promoting Perl?)

/I3az/

PS. Some blog house keeping:

  • Removed use Perl; from my link list. Not much going on their front page these days and it doesn’t look very appealing if you go there with no login/profile.
  • Added YAPC TV to my link list.
  • And also Presenting Perl
  • And yes there are no ironman badges at moment (since ironman site upgrade)

Podcasts & Perl

April 30, 2010
tags: ,

I’m an avid listening of tech podcasts. My podcast subscription list is so large I have a backlog that in some cases stretch back a year.. sometimes two!

There are some podcasts where I do keep upto date with (MacBreak Weekly, TwiT), while there are others I dip in and out of as my time and mood dictates.

Early this year I encountered a Perl conjunction among my podcast listening which culminated in Merlin Mann shouting “Perl, Perl, Perl” in MacBreak Weekly 182: There’s An App For That.

This was the main inspiration for me to write yesterday’s post. Today’s follow up is simply to list all the Perl “related” podcasts that I listened to:

FLOSS Weekly
Opensource podcast hosted by Leo Laporte with Randal Schwartz or Chis DiBona. Below are feature episodes in this podcast series:

Linux Outlaw
Linux and opensource podcast. The following were on episodes of the podcast:

This Week In Tech
Weekly tech roundtable with Leo Laporte at the helm. Below were guests on TwiT (see yesterdays post)

I’ll finish off by mentioning a wonderful dedicated Perl podcast from the Portland Perl Mongers who provide recordings of their regular talks.

/I3az/

PS. I would have also like to have included Perlcast but it appears to have fallen off the web. And Perlcast twitter hasn’t been updated since May 2009 :(

Hopefully it will return in not too distant future?

Follow

Get every new post delivered to your Inbox.