Extract Ranges Permalink

Perl Added less than a year ago and last edited less than a year ago

I'm sure there is a module to do this already, but as as a Perl exercise this morning I wrote the below. It extracts specified arithmetic sequences from arrays of numbers:

#!/usr/bin/perl

use strict;
use warnings;

use Data::Dumper;

sub getr {
    my $inc = shift;
    my @list = @_;
    my @thislist;
    push(@thislist, shift @list);
    while (my $i = shift @list) {
        if ($i == $thislist[-1] + $inc) {
            push(@thislist, $i);
        }
        else {
            return ( \@thislist, getr($inc, $i, @list) );
        }
    }
    return \@thislist;
}

my @a = qw(1 2 3 4 7 8 9 11 12 16 18 20 21 22 25);
my @b = qw(2 4 6 8 10 11 13 15 17 19 20 21 22 24);
my @c = qw(10 7 4 1 -1 -9 -10 -11 -12 -15 -18);

my @lists = getr(1, @a);
for my $list (@lists) {
    print "Got: @$list\n";
}

print "\n---\n";

@lists = getr(2, @b);
for my $list (@lists) {
    print "Got: @$list\n";
}

print "\n---\n";

@lists = getr(-3, @c);
for my $list (@lists) {
    print "Got: @$list\n";
}

The output:

Got: 1 2 3 4
Got: 7 8 9
Got: 11 12
Got: 16
Got: 18
Got: 20 21 22
Got: 25

---
Got: 2 4 6 8 10
Got: 11 13 15 17 19
Got: 20
Got: 21
Got: 22 24

---
Got: 10 7 4 1
Got: -1
Got: -9
Got: -10
Got: -11
Got: -12 -15 -18

I'll clean it up and put it in a package soon - I think I will start keeping a personal code snippet/exercise git repo - it might be good to look back on as a journal!

Colophon

Django Python 960.gs Git Vim NetBSD Nginx

The Author

The author is a software engineer living in Australia. He sux at guitar, loves camping, doesn't like cake, does like coffee and is a lazy home brewer.

Meta

Help
Latest entries

*BSD Agile Apache Apple Athletics Beer Best-Practice Censorship Comedy Cool Crosswords Deployment Django English Exim Firefox Git Hardcore Health Interface irssi Javascript Jira Languages Linux Makefile Markdown Mathematics Mobile Broadband MySQL NetBSD nginx Nokia OSX Perl Photo Privacy Python Rant Requirements rsync Ruby Shell Slackware SQL SQLite SSH Standards Subversion Testing ThisBlog Vim VMWare (Fusion) VPN WDTEM X Yum zsh

Recent Entries

Perldoc Output
Yum
Possum
Git's Index
Jira Project Keys
The Coffee Shop
Git GUI
It is more important...
Questioning Unix (and Other) File Times
The Frog King Photo
Rain Cloud Photo
rsync
Timezone
utf8 in your Perl
Theatre Ceiling Photo
Some problems are so complex...
Colours in your PAGER
zsh vared
zsh magic-equals and double-star
Funny Tweets

Links

ChoppingBoard, Project365, RageQuit

♥ Actors/Artists/Characters