Notes on Arrays in Perl, Take Two

My Perl is really weak what with only having read “Learning Perl” so far…. I continue to write little programs in the langauge in spite of my unfamiliarity with Perl idioms and without having assimilated all of the available material. In my day job, I pretty much never get any code reviews or even any tips and tricks, so I try to take advantage of the feedback I get on this blog. So here’s a rewrite of portions of what I posted the other day in order to try to synthesize suggestions I received from a “real” Perl coder.

#!/usr/bin/perl
# demonstrate a sub that returns an array of arrays
# thanks to Eric TF Bat for the code review

# note: read the Camel book or your Perl code will be really annoying
@bar = makearray(1,8,27);
showme(@bar);
print "This is still crazy:\n";
&crazy;

sub makearray {
    return @_;
}

sub showme {
    my @args = @_;
    foreach my $i (0..2) {
	# use $args[], not @args[]
	print "$args[$i]\n";
    }
}

sub threearrays {
    my @one, @two, @three;

    # assign $_ to a local variable for readability
    foreach my $i(0..2){
	$one[$i] = ($i + 1) * 1;
	$two[$i] = ($i + 1) * 2;
	$three[$i] = ($i + 1) * 3;
    }

    my @all;
    $all[0] = \@one;
    $all[1] = \@two;
    $all[2] = \@three;
    return @all;
}

sub crazy {
    my @x = &threearrays;
    my @a = @{$x[0]};
    my @b = @{$x[1]};
    my @c = @{$x[2]};
    showme(@a);
    showme(@b);
    showme(@c);
}
Advertisements

7 Responses to “Notes on Arrays in Perl, Take Two”

  1. Perl Coding School » Blog Archive » perl code [2008-07-20 19:04:35] Says:

    […] Notes on Arrays in Perl, Take Two By lispy usr/bin/perl # demonstrate a sub that returns an array of arrays # thanks to Eric TF Bat for the code review # note: read the Camel book or your Perl code will be really annoying @bar = makearray(1,8,27); showme(@bar); print "This is … Learning Lisp – https://lispy.wordpress.com […]

  2. Geno Z Heinlein Says:

    Let me strongly second the recommendation for the Camel book. It has an entire section just on arrays of arrays, arrays of hashes, et cetera. My perl still looks somewhat C-ish, but to the degree that I have mastered idiomatic perl, I owe it to the camel book.

  3. Eric TF Bat Says:

    Well, now, if I’d known I was doing a code review (rather than, say, helping a fellow Lisper to avoid embarrassment if the Perl fanboyz happened to notice his blog) then I’d’ve said much more — about ‘use strict’ and ‘use warnings’, about not needing the ampersand sigil on function calls, about using prototypes in the arguments to functions, and about the usefulness of hashes as a self-documenting way to wade through complex structures made even more complex by Perl’s uniquely 1940ish attitude toward data typing. But really, that comment about the Camel book is all I needed to say: run, do not walk, to the nearest bookshop or O’Reilly website and get yourself the Camel. It is one of the four or five best books on programming ever written – up there with Kernighan and Ritchie, SICP, Brodie’s Starting Forth, and a few other greats.

  4. lispy Says:

    Downloaded it last night and I’m halfway through that opening section covering arrays and hashes. It was exactly what I needed. Thanks.

    I’d tried to pick it up a few years ago, but either I was brain damaged or it was an early edition or I hadn’t done enough “Learning Perl” or something– I went into shock when I peeked at the OOP coverage. Now that I’m aware of the existence of Smalltalk and CLOS, I think I can keep my breakfast down this time. (I notice that the package system reminds me of Common Lisp…. And hey… big arrows are just commas… which means that hashes are just lists…. And @ stands for array, $ for scalar, and % represents the key/value pair [if you squint].)

  5. draegtun Says:

    Don’t know if this will help but here is a slightly more idiomatic version…..

    use strict;
    use warnings;
    
    my @bar = ( 1, 8, 27 );
    showme( @bar );
    print "This is still crazy:\n";
    crazy();
    
    sub showme { say $_ for @_ }
    
    sub threearrays {
        my ( @one, @two, @three );
    
        foreach my $i ( 0..2 ) {
        	push @one,   ( $i + 1 ) * 1;
        	push @two,   ( $i + 1 ) * 2;
        	push @three, ( $i + 1 ) * 3;
        }
    
        return ( \@one, \@two, \@three );
    }
    
    sub crazy {
        my ($a, $b, $c) = threearrays();
        showme( @$a );
        showme( @$b );
        showme( @$c );
    }
    
    

    Things to note….

    1) Like Eric says do use strict & warnings. They’ll save u’re life in the long run! (for eg. your… my @one, @two, @three doesn’t do what u think… only @one is lexical).

    2) mkarray sub is superfluous (as are the & prefixes to the calls)

    3) “say” is a addition to Perl 5.10 which is print with automatic newline.

    4) And another vote for “Programming Perl” Camel book. If u intend to further your Perl then I highly recommend “Higher Order Perl” & “Perl Best Practises”.

    Always best to use list features of Perl as opposed to arrays. More idiomatic and probably more Lispy 😉

    And u can improve on above even further, for eg…..


    sub crazy2 {
    showme( @$_ ) for threearrays();
    }

    Above is starting to look a lot prettier… definitely no fingernails in this oatmeal 😉

    PS. Got any questions then fire away. There’s a lot of beauty & power in Perl but u have to scratch back its veneer to see its inner beauty.

    PPS. re: CLOS. U should have a look at moose.perl.org then… u may find this interesting.

    /I3az/

  6. lispy Says:

    Nice.

    I figured out the “return ( \@one, \@two, \@three );” on my own this morning… but I beat my head into the wall trying to make something like “my ($a, $b, $c) = threearrays();” work.

    Also… I found out (I think) that using the ampersand is not just superfluous, but dangerouse as well: it overrides any prototyping that you might have set up…!

    Thanks a lot. This issue has been bugging me for a month now…

  7. draegtun Says:

    Perl has lots of DWIM sprinkled around… which can be handy but can also mean lots of places to trip over until u’re fully familiar with things!

    Its important to understand how lists work in different contexts. Here’s one Perlmonks discussion which may help…. http://www.perlmonks.org/?node_id=72247

    /I3az/

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: