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

auto increment.. 1

Status
Not open for further replies.

perlone

Programmer
May 20, 2001
438
US
I have a file called weapons.txt and it contains the following:

Shot Gun
Counter Strike
Strike Forces


And on the main script, I have the following:

$count_weapons=1;
foreach $weapons (@weapons) {
$weapon_list .= &quot;$weapons<BR>&quot;;
$count_weapons++;
}

When i run the script, it counting 4 instead of 3. I also tried with $count_weapons = 0 and the results were the same. Is it something has to do with the new line?




 
Your weapon count needs to start at zero, not one. Before the first interation of your loop you have zero weapons, not one.

just loose the line =>'$count_weapons=1;'

Another slant....... you could get the length of an array like,
@weapons = ('first','second','third');
$num_weapons = $#weapons;


keep the rudder amid ship and beware the odd typo
 
Like I said earlier i did tried giving the value 0 but the results were same but i never thought of the $num_weapons = $#weapons. Thanks.
 
Still not working and I cannot do this:
@weapons = ('first','second','third');

Because it's reading from a file called weapons.txt. Here's my full code now:

open(F, &quot;$basedir/$email/weapons.cgi&quot;);
@weapons = <F>;
close(F);

$count_weapons = 0;
foreach $weapons (@weapons) {
$weapon_list .= $weapons&quot;<BR>&quot;;
$count_weapons++;
}
 
is this what you are trying to do???

open(F, &quot;weapons.txt&quot;);
while(<F>)
{
chop;
@weapons = <F>;
}
close(F);
$count_weapons = @weapons;

$string=join(&quot;<BR>&quot;,@weapons);
print $string;

 
@weapons=<F> should be this

@weapons=(@weapons,$_);
 
Instead of looping thru the file and adding each line to the array (which would be better done with push anyway), just do like you were doing before and use @weapons = <F>. If you need to remove the \n from the end of each record you can do this:
Code:
@weapons = map(chomp,@weapons);
Note that $#weapons will give you the subscript of the last element of @weapons, not the number of entries. scalar(@weapons) will give you the number of entries.

The way isivt gave for printing the array will work great. You may also want to add a &quot;<br>&quot; to the end of the string too.
Tracy Dryden
tracy@bydisn.com

Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top