Fwd: Re: [NCLUG] Looking at programming languages...

Bob Proulx bob at proulx.com
Thu Jan 17 15:44:47 MST 2008


Sean Reifschneider wrote:
> My biggest problem in Perl was that I always had problems passing a list to
> a function.  The function always wanted to unpack the list into separate
> arguments for the function.  I was never able to find the documentation
> that appropriately educated me on what the story with passing arguments to
> functions was.  This was back in 1996-ish, and I think I saw a reference to
> some documentation that "fixed" this, but by that time I was too happy with
> Python...

This is not to advocate returning to Perl but simply to address the
question from an academic standpoint...  I hate unanswered questions.

In Perl arrays passed as arguments are placed into the @_ array along
with other arguments.  Which means that passing one array is easy.
Just use the @_ variable.  But the problem is that passing two arrays
sees them merged together in the @_ array.

One idiomatic way to pass an array to a function in perl is to use a
reference.  Pass the arrays in by reference and then use the pointer
to them.

  #!/usr/bin/perl
  sub foo {
      my $arr = shift;
      print "foo: ", join(', ',@$arr), "\n";
  }
  my @arr = ( 1, 2, 42 );
  &foo(\@arr);
  exit(0);

Here the \ character quotes the @arr variable and creates a reference
to it so \@arr is a reference to @arr.  Later $arr is a reference and
therefore in Perl @$arr is the array part of the typeglob reference.

Perl references and complex data structures are explained in Advanced
Perl Programming by Sriram Srinivasan.  The first four chapters are
required reading for Perl programmers.  The topics should have been
better addressed in the Perl Camel book but were not.

An excellent book on Perl in general is Object Oriented Perl by Damian
Conway.  You might think it is a book targetting OOP and the latter
half of the book does do that but the first half of the book details
Perl's syntax and data structures.  The detailed Perl section has
nothing to do with OOP but is simply a good Perl section.  For example
it explains Perl typeglobs in detail.  I highly recommend this book.

Bob



More information about the NCLUG mailing list