Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

array manipulation question 2

Status
Not open for further replies.

ailse

Programmer
Jan 20, 2004
79
GB
Hi,

I am trying to print an array such that each element is followed by the next one, with a tab character in between, and then a new line, so that:

Code:
@array = ("a", "b", "c", "d");

will be displayed as:

Code:
a   b
b   c
c   d

so far my code is:

Code:
my $i;

my @array = ("a", "b", "c", "d");

my $size = @array;

for ($i = 0; $i < $size; $i++) {
	print $array[$i] . "\t" . $array[$i+1] . "\n";
}

which is *sort of* working alright, except the result i'm getting with it is

Code:
a       b
b       c
c       d
Use of uninitialized value in concatenation (.) or string at next_array.pl line 13.
d

the first three lines are fine, but i don't want it to be "circular" i.e i need to stop it after the last item in the array, hope that makes sense. any tips on how to fix this would be great :)
 
Just stop the loop one element earler:
Code:
for ($i = 0; $i < $size - 1; $i++) {

Or more perlishly:
Code:
for my $i ( 0 .. $size - 2 ) {
 
Code:
for ($i = 0; $i < @array; $i++) {
    print $array[$i];
    print $i % 2 ? "\t" : "\n";
}
Note: not tested, but should produce
Code:
a     b
c     d
e
Is that what you want?


Steve

[small]"Every program can be reduced by one instruction, and every program has at least one bug. Therefore, any program can be reduced to one instruction which doesn't work." (Object::perlDesignPatterns)[/small]
 
thanks steve - but no, that's not quite what i was after, i didn't want the array to "loop round" as it were, so once the final value in the array is reached, the loop should stop. ishnid's suggestion has produced the output i wanted :)
 
Just trying to kill time...
Code:
for (my $i = 0; $i <= $#array; $i+=2) {
    print $array[$i], $array[$i+1] ? "\t$array[$i+1]\n" : "\n";
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top