Showing posts with label perl. Show all posts
Showing posts with label perl. Show all posts

Monday, 2 July 2012

Programming languages should be self documenting

Perl 5.16.0, the latest and most greatest release in Perl's 20+ year history of being awesome added a new keyword that I never knew I wanted. I will illustrate by starting in the past.

The following is a complicated way to calculate triangular numbers, that uses recursion, the best technique in computer science:

sub triangle {
  my $num = shift;
  return 1 if $num == 1;
  return $num + triangle($num-1);
}


That's all very trivial, and in this short example it's very obvious that we're using recursion as the subroutine is so short that the name is very close to our recursive call.

Now, the technique of recursion is very useful in more complex problems, especially those operating on graphs, where the subroutine body might be more than a couple of lines long, in which case I'd have to add the annoying comment to remind the reader what's going on:

sub triangle {
  my $num = shift;
  return 1 if $num == 1;
  return $num + triangle($num-1); # recurses!
}

and, if and when I decide to refactor this subroutine, I need to remember to change the name of the subroutine, and the name I use when I call it. This is entirely pointless busywork.

Instead, now, Perl has introduced the __SUB__ keyword which magically turns into the subroutine you're currently in:

use v5.16;
sub triangle {
  my $num = shift;
  return 1 if $num == 1;
  return $num + __SUB__->($num-1);
}

which is both clearer to read and immune to me changing the name of the routine, and, as a bonus, it's helpful if Perl wants to transform the subroutine for the sake of efficiency.

I never missed this little feature, but now it exists it's so natural that I'm surprised that it never existed until now. That's the sign of a perfect addition to a language.

Friday, 3 June 2011

Saving me from myself

The great thing about using Perl to schedule the generation of your LaTeX documents, is that you can also use the Perl to catch a bunch of little mistakes that make life unpleasant in non-obvious ways. One of my favourites is to put the \label before the \caption in the figure environment, because, of course, in any sane world you could do that, but not in LaTeX. Thus, Perl to the rescue:

method check_figure_labels {
    my $file = $self->src;
    my ($in_figure, $seen_caption) = 0;
    foreach my $line (read_file($file)) {
      $line =~ s/%.*$//; # strip comments
      given ($line) {
        when (/\\end{document}/) {
          last;
        }
        when (/\\begin{figure}/) {
          $in_figure = 1;
        }
        when (/\\end{figure}/) {
          $seen_caption = 0;
          $in_figure = 0;
        }
        next unless $in_figure;
        when (/\\caption/) {
          $seen_caption = 1;
        }
        when (/\\label{(.*?)}/) {
          die "Label for LATEX figure $1 comes before the \\caption you will hate yourself later\n"
            unless $seen_caption;
        }
      }
    }
}

Also, sometimes I cannot spell the names of famous (and awesome) physicists:

method check_rayleigh {
    my $file = $self->src;
    my $latex = read_file($file);
    if ($latex =~ /raleigh/i) {
       die "YOU ARE A MORON! RAYLEIGH HAS A Y IN IT!";
    }
    return;
}

Sunday, 29 May 2011

Moose the revenge

19:56 I continued my immersion in things Moose and dived past MooseX::Method::Signatures which was quite the groovy and on into MooseX::Declare. MooseX::Declare seemed like such a wonderful thing, until I wrapped it around my otherwise perfectly functioning class and BOOM! four thousand lines of errors and no idea why or where. Long story short, I'd coincidentally deleted the leading { in "$ENV{HOME}/blah" so the code inside the class was invalid. Fine, don't compile, but please DON'T JUST EXPLODE perhaps say why you've decided to explode and provide a useful error. I like Moose a lot, I'll be using it, but I'll be very cautious of any programming language (for that is what Moose is) which won't tell me where I've gone wrong.

20:00 Right, so now I'm going to go home and eat.

In which Alex learns Moose

Today I have decided to learn Moose.  I shall do this by converting my spider-web latex generation master script, now existing in four different incarnations, into an application class.  It will be easy! Or will it?  I liveblog myself, thus:

15:00 Finally decide to be productive (it is Sunday).
15:01 Decide to re-write generate.pl
15:02 type 'perl -MCPAN -e shell' 'install MooseX::Getopt'
15:12 While waiting for Moose to install, decide to liveblog myself.  The install is taking a whole long while...
15:16 Meanwhile, I have written this, which I hope will work:

package MyApp::Generate;
use Moose;
with 'MooseX::Getopt';

has small => (is => 'rw', isa => 'Int', default => 0);

1;

15:23 Still waiting for Moose to build and test and install. I'd like to at least run perl -c on my snippet to see if I'm a fool or not, but as yet, I'm ignorant even of my foolishness.

15:29 Oh, there we are, installed. Time to try the very basic:

use 5.12.0;
use lib "$ENV{HOME}/alexwork/perl/";
use MyApp::Generate;

my $app = MyApp::Generate->new_from_opts();

15:33 Well, that works at least. Now, to make things work. (This might take a while).
15:38 So, I want a list of somethings, but not have it be commandline-able, this can be done using an attribute with a leading underscore:

has '_lib' => (accessor => 'lib', isa => 'ArrayRef[Str]', default => ['lib']);

15:47 Well, that didn't work, an enormous error (can I stop these enormous traces?) tells me I can't have a reference as a default, but I can have a sub to wrap it, so I do that.
16:12 Importing the crufty methods and changing the million script-local my variables into attributes of the class. How do I get a the entries of a HashRef attribute?
16:15 By which I mean, get in a tidy manner. For now I'll just grab it and use it.
16:28 still bashing in methods. Wondering what the output of an 'ArrayRef' attribute will be, a list or a reference. Not immediately clear.
16:35 well, it runs, but I want to have my options just as '--nopdf'. Maybe I can't do this, that would be sad.
16:39 Ah, I need to make the attributes be 'Bool' then MooseX::Getopt figures it out fine. Not all sad, happy even.
16:41 Now having trouble with a builder method. It's getting called, I'm going to find out what with.
16:45 As expected, I'm now in a confused state where I'm not quite sure why this method is being called.
16:46 so it looks like it's being called as part of the ->new_with_options during object construction, so maybe the builder is called when a default value is created...
16:48 Yes, this is so. I've added a guard for the default case.
16:50 I've constructed my object, now I fail to access an ArrayRef attribute correctly. What should it be?
16:51 It is indeed an array reference.
16:53 Now it seems I don't understand what a builder is for. Perhaps I really just need to write my own set_foo which then sets other things (I have an option which sets lots of things).
17:03 Well, I didn't. A builder is a different way to set a default, but to be able to override this in subclasses. I really want a trigger which will then go and set the other attributes.
17:06 Hmm, I can't suggest a trigger to be a method. For now this isn't a problem.

has src => (is => 'rw', isa => 'Str', default => '', trigger => \&_src_set);
sub _src_set {
    my $self = shift;
    my $val = shift;
    return unless defined($val);
    $val =~ s/\.tex$//;
    $self->out($val);
}

17:14 This now works for the first script, let's see if I can impose the class on the other generation routines without too much crying...
17:25 Different journals have their quirks, so it's time for a subclass instead of a slightly different but otherwise the same script.
17:35 Well, that was nice and easy.

Moral of the story: That was really very easy.

Next is to use more than just Moose. I think I like MooseX::Method::Signatures; One trouble, with picking all this up, it's that it's not clear what's worth picking up.

Friday, 29 October 2010

proj4 and Perl for windows

All amazing people the world over use Perl to get stuff done. Sometimes the world conspires to make this a tiny bit harder than it should be. Today I want to convert coordinates using the proj4 library, but could not because the geo::proj4 library doesn't build nicely under windows. But, ugly to the rescue:

2) Do the ugly:

# this works, would you adam and eve it
sub coords2pols {
my ($lat, $lon) = @_;
if ($lon > -50) {
($lon, $lat) = ($lat, $lon);
}

open my $fhi, '>tmp.txt' or die "tmp file $!";
print $fhi "$lon $lat\n";
close $fhi;

system('cs2cs +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs +to +proj=stere +lat_0=-90 +lat_ts=-71 +lon_0=0 +k=1 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs tmp.txt > tmp.out.txt') and die "$@";
open my $fh, '
my $line = <$fh>;
close($fh);
chomp($line);
my ($x, $y) = split(/\s+/, $line);
unlink('tmp.txt');
unlink('tmp.out.txt');
($x, $y);
}