PDA

View Full Version : incrementing


bazz
07-03-2005, 05:19 PM
I was reading about incrementing ++ last night but can't work out how to apply it.

I have a variable which represents a lot of values which are in a hash.

If I wrote:

foreach ($distance <= $radius) { $true ==1;
print "There are $true++ $businessType within $radius Km.\n";
}


It would probably be wrong but might help to explain my efforts.

I want to output a number such as 35 which is the number of times the variable is true.

bazz
07-03-2005, 05:47 PM
I think I got it but I would apreciate a second opinion. After all, I have only one listed so it'll say 1 if its syntactically correct which it apparently is. :)


if ($distance <= $radius) { $true++;
if ($true == 1) {
my $isAre = "is";
print <<EOF;
There $isAre $true $businessType within $radius Km.;
EOF
} else {
my $isAre = "are";
print <<EOF;
There $isAre $true $businessType within $radius Km.
EOF
}

}



Finally, I think the wheels of perl coding are starting to turn. YAY!!

Bazz

FishMonger
07-03-2005, 06:52 PM
++$true # preincrement
$true++ # postincrement
_____________________

You can reduce the code by using the trinary operator.
http://www.unix.org.ua/orelly/perl/prog3/ch03_16.htm

($distance <= $radius && ++$true == 1) ? $isAre = "is" : $isAre = "are";

print <<EOF;
There $isAre $true $businessType within $radius Km.
EOF

bazz
07-03-2005, 07:41 PM
Fishmonger, Thanks.

I had to take a few moments to understand that.

I shall try to tweak it coz it seems to print out once, for each listed restaurant. (I have added a second one to help give a more accurate test so I get output from that line beside each restaurant name, when I only want the line once. Still, I hope I can manage that :)

Bazz

rwedge
07-03-2005, 10:50 PM
Here's another example:my @distance=(30,23,44,76,143,12,23,24,66);
my $radius = 30;

my $x=0;
foreach my $d (@distance) {
if ($d <= $radius) { $x++; }
}

if ($x == 0) { print "No results were found within $radius Km\n"; }
elsif ($x == 1) { print "There is 1 location within $radius Km\n"; }
else { print "There are $x locations within $radius Km\n"; }

-or-

my $true =($x == 0)? "No results were found within $radius Km\n":
($x == 1)? "There is 1 location within $radius Km\n":
"There are $x locations within $radius Km\n";
print $true;

you could reduce the conditional a little more: $isAre = ($distance <= $radius && ++$true == 1) ? 'is': 'are';