ASPN ActiveState Programmer Network
ActiveState
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups


Recent Messages
List Archives
About the List
List Leaders
Subscription Options

View Subscriptions
Help

View by Topic
ActiveState
.NET Framework
Open Source
Perl
PHP
Python
Tcl
Web Services
XML & XSLT

View by Category
Database
General
SOAP
System Administration
Tools
User Interfaces
Web Programming
XML Programming


MyASPN >> Mail Archive >> activeperl
activeperl
Re: Sub returning a scalar and an array ref?
by Todd Beverly other posts by this author
Aug 1 2007 12:15PM messages near this date
Re: Sub returning a scalar and an array ref? | Using Sessions to save Parameters
Deane.Rothenmaier@[...].com wrote:
> 
>  Gurus,
> 
>  Is it possible for a subroutine to return both a scalar (an integer, 
>  specifically) *and* a reference to an array of arrays?
> 
>  Current code returns just the array ref, with the scalar push-ed onto 
>  the end of the referenced array. I'm hoping to get rid of the kludge, 
>  and I've not found much help in the camel (LITWP, maybe?).  Here's 
>  sample code:
> 
>  # sub adds a row to the passed array (of arrays) and returns it, along 
>  with incremented counter
>  sub add_row {
>  my ($counter, @ary) = @_;
> 
>     # do stuff to @ary...
> 
>     # add scalar to @ary:
>     push( @ary, ++$counter );
> 
>     return( \@ary );
>  }
> 
>  # sample call:
>  @added_stuff = @{ add_row( $out_count, @added_stuff) };
>  $out_count = pop( @added_stuff );
> 
>  I know there's gotta be a cleaner way to do this, but my brain's 
>  frozen on this one.
> 
You could do something like this:
#!/usr/bin/perl -w
use strict;

my @ary = qw(1 2 3);
my $oldcount = 5;

my ($count, $ref_ary) = add_row($oldcount, @ary);
@ary = @{$ref_ary};

print "ary is now: ", join(', ', @ary), "  count is $count\n";

sub add_row {
my ($counter, @ary) = @_;

   # do stuff to @ary...

   # add scalar to @ary:
   push( @ary, ++$counter );

   return($counter, \@ary );
}

Or this, if you don't have to return a reference to an array.
#!/usr/bin/perl -w
use strict;

my @ary = qw(1 2 3);
my $oldcount = 5;

my $count;
($count, @ary) = add_row($oldcount, @ary);

print "ary is now: ", join(', ', @ary), "  count is $count\n";

sub add_row {
my ($counter, @ary) = @_;

   # do stuff to @ary...

   # add scalar to @ary:
   push( @ary, ++$counter );

   return($counter, @ary );
}

_______________________________________________
ActivePerl mailing list
ActivePerl@[...].com
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs
Thread:
Deane Rothenmaier
Andy Bach
Todd Beverly

Privacy Policy | Email Opt-out | Feedback | Syndication
© ActiveState Software Inc. All rights reserved