For a thing (that you may hear more about at some point in the future) I needed diagrams of traffic lights. But Google Image Search didn’t really have what I was looking for. Everything was either too realistic or not CC-licensed so I couldn’t use the images how I wanted.

So I decided to do it myself. But I’m not exactly artistic. I far prefer it when I can get computers to draw images for me. I’ve dabbled with SVG before and it seemed like the perfect tool for the job. And there’s a module from CPAN that makes it simple to create SVG images from Perl.

It only took an hour or so before I was drawing images like the one above – which was exactly what I was looking for.

Initially, I shared my code as a Gist, but since then I’ve extracted the useful bits into a module which I’ve uploaded to CPAN as SVG::TrafficLight. I’ve tried to make it as configurable as possible, so you should be able to use it for all your traffic light drawing needs as well.

Starting to use it is pretty simple.

Basic use of SVG::TrafficLight use SVG::TrafficLight; my $tl = SVG::TrafficLight->new; # default image print $some_file_handle $tl->xmlify; 1 2 3 4 use SVG:: TrafficLight ; my $tl = SVG:: TrafficLight-> new ; # default image print $some_file_handle $tl -> xmlify ;

The default sequence of lights shows the UK’s standard traffic light sequence (green, amber, red, red and amber, green) but it’s simple enough to produce a different sequence (even one that you would never see on the roads).

A different sequence of lights my $tl2 = SVG::TrafficLight->new({ sequence => [ { red => 1, amber => 1, green => 1 }, # all lights on { red => 0, amber => 0, green => 0 }, # all lights off ], }); 1 2 3 4 5 6 my $tl2 = SVG:: TrafficLight -> new ( { sequence = > [ { red = > 1 , amber = > 1 , green = > 1 } , # all lights on { red = > 0 , amber = > 0 , green = > 0 } , # all lights off ] , } ) ;

If you read the documentation, you’ll see how you can customise pretty much anything in the diagram – the size of the lights, the padding between them, even the colours used.

Let me know if you find it all at useful. SVG is fun. I’ll think I’ll investigate it some more.

Also published on Medium.