in reply to Re: printing arrays
in thread printing arrays

Hi dave, thanks for your solution, but how can I 'pad' out the shorter arrays? AM

Replies are listed 'Best First'.
Re: Re: Re: printing arrays
by davido (Cardinal) on May 06, 2004 at 15:49 UTC
    That's something you'll have to decide. Do you want them padded at the end, or at the beginning? Do you want them padded with empty strings, or zeros? The one thing you shouldn't do is leave them different lengths.

    Here's a subroutine you can use to "end pad" arrays with whatever string you prefer... as many arrays as you want.

    sub padarrays { my $padchar = shift; my @arrays = @_; my $max = 0; foreach my $aref ( @arrays ) { $max = ( @{$aref} > $max ) ? @{$aref} : $max; } foreach my $aref ( @arrays ) { my $padqty = $max - @{$aref}; next unless $padqty; push @{$aref}, $padchar x $padqty; } }

    The sub takes as its first argument a string (it can be empty, a number, or characters) that should be used to pad each array. It takes a list of array refs as the remainder of its parameters. It will then check the length of each array finding the longest, and pad all the rest of the arrays with your pad character so that they're all the same length.

    I didn't have time to test it, you may have to tweak a little to get it to work right. caviet emptor.


    Dave