bjohn has asked for the wisdom of the Perl Monks concerning the following question:

ok guys for some reason it is not counting the values entered by the user.
#!/usr/bin/perl/ print "enter values.\n"; @value = (); while ($value = <>){ chomp($value); if ($value eq ""){ last;} @value = (@value , $value); } $count = 0; foreach $line (@value) { $count++; @z =split('', $line); $count = @z; } print "$count items\n"; exit;

Replies are listed 'Best First'.
Re: having trouble with count
by toolic (Bishop) on Mar 22, 2011 at 14:04 UTC
    $count++; @z =split('', $line); $count = @z;
    Your 2nd assignment to the $count variable clobbers the 1st ($count++).

    You should show the data values you input as well as the output you want. That way it will be clearer to us what you are trying to accomplish. Also, use strict and warnings.

      thx tht fixed it
Re: having trouble with count
by johngg (Canon) on Mar 22, 2011 at 14:18 UTC

    Some pointers.

    • Always put use strict; and use warnings at the top of your scripts and declare your variables with my as this will save you time tracking down errors.

    • Always indent your code to make it easier to follow the logical flow and be consistent.

    • It is probably better not to have a scalar and an array both called value as this can lead to confusion. Make the array @values as it better describes its purpose.

    • Why are you incrementing the $count by one every time through the loop rather than adding the value as entered and held in $line to it?

    • Why are you spliting the each value into individual characters then setting $count to the number of characters (array in scalar context returns number of elements), thus undoing any previous work of accumulating a total?

    Your problem lies with those last two points. Have a think about the logic required to accumulate a series of values.

    Cheers,

    JohnGG

Re: having trouble with count
by choroba (Cardinal) on Mar 22, 2011 at 14:12 UTC
    The code does what you tell it to do:
    $count = @z;
    Also, instead of
    @value = (@value , $value);
    you'd normally use
    push @value,$value;
    (and it is usually not a good idea to have two variables with the same name)