On Sun, May 10, 2009 at 13:06, AndrewMcHorney <andrewmchor...@cox.net> wrote:
> Hello
>
> I need a little assistance in creating a function for my perl code. The
> function will pass in an array of strings and an index. The function will
> build a single string using the 1st string at the passed in index and the
> remaining strings in the array. It will return the newly built in string.
snip

This really does not deserve a function, it sounds like you just want

my $string = join '', @array[$index .. $#array];

but you may want a function if you want to be able to use negative
indices (i.e. ones that start from the end of the array, rather than
the start) or be certain the index is in the range of items in the
array:

#!/usr/bin/perl

use strict;
use warnings;
use Carp;

sub build_string {
        my ($array, $index) = @_;

        #get the real index so the range operator below works right
        $index += @$array if $index < 0;

        croak "index $index is not in the range 0 to $#$array"
                if $index < 0 or $index > $#$array;
        return join '', @{$array}[$index .. $#$array];
}

my @a = 0 .. 9;

for my $i (reverse(-11 .. -1), 0 .. 10) {
        my $s;
        eval {
                $s = build_string(\...@a, $i);
                1;
        } or do {
                print $@;
                next;
        };
        print "index $i: $s\n"
}

-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to