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 Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Print Question

Status
Not open for further replies.

tar565

Programmer
Jan 24, 2005
39
0
0
IE
I am having one of those monday mornings!!!! Can some please tell me why the following 2 lines print the string with the array position at the begining of each line.

eg


0Hello
1I am well
2How are you
.
.
.

I know it is simple but i cant see it.
$FileString doesnt contain the index at all.

my @Lines = split(/\n/,$FileString);
print "$Lines[$i]\n", $i++ while ($i < $LineNum);
 
The reason it's printing the array id is because you're telling the system to print it in the statement print "$Lines[$i]\n", $i++. The part in bold is where the print is occurring.

- Rieekan
 
Just to elaborate on what Rieekan posted: The print function takes a list as its argument and prints each element of the list. In the code you posted, the first element of the list is "$Lines[$i]\n" and the second is $i++, which is why both are getting printed. Either of these will do what you're looking for:
Code:
print "$Lines[$i]\n" && $i++ while ($i < $LineNum);

# or ...

print "$Lines[$i++]\n" while ($i < $LineNum);
 
To make your bit of code work, you can modify it to read something like:
Code:
print("$Lines[$i]\n"), $i++ while ($i < $LineNum);

However, you basically used a while loop like a for/foreach loop. This does the same thing:
Code:
foreach ($i = 0; $i < $LineNum; $i++) {
    print("$Lines[$i]\n");
}

Or, to shorten that up a bit (and use a structure similar to your original) and print every element in @Lines:
Code:
print "$_\n" foreach (@Lines)
 
Thanks I am in another world today.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top