[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

# Re: OT:Perl %= operator

```On Thu, Aug 02, 2001 at 08:28:32PM -0400, Ken Januski wrote:
> I've been reading the most recent Randall Schwartz column in SysAdmin
> magazine and his code has this line:
> (\$start +=1) %=7;
> If \$start = 1 then I think that this line means 2%7. I believe that the
> intended result is 2 but I'm just not sure what 2 % 7 equals. I know
> that 7%2 = 1 but I'm not sure what happens with modulus when the 2nd
> number is greater than the first. I've gone through about 6 books
> looking for the answer but none of them consider the case where the 2nd
> number is larger than the first.

% is modulo, which is the remainder after division:

print \$value - (int(\$value / \$divisor) * \$divisor),"==",\$value % \$divisor;

for any \$value and \$divisor.

@weekday = qw(sun mon tue wed thu fri sat);
\$offset = 1; # maybe our span starts on monday
foreach \$day ( 1..60 ) {
my \$wd = \$day + \$offset;
print "day \$day is a ",\$weekday[\$wd % 7]," (",\$wd % 7,")\n";
}

with randall's algorithm, he's wrapping his variable around
so that it always stays between 0<=\$start<7 with %=:

\$start++;
\$start = \$start % 7;
# or (\$start++) %= 7 for short

he could just calculate the modulo when it's needed and let
\$start creep higher and higher -- after all, 52 % 7 is still
3 -- but <guess> it may take a few more clock cycles to
calculate modulos of larger values </guess> but i don't really
know for sure.

\$val % \$val is not to be confused with '%hash' as in

%mon = (
jan => 31,
feb => (\$year % 400 ? 29 : \$year % 100 ? 28 : \$year % 4 ? 29 : 28),
mar => 31,
apr => 30,
#...
);
\$hash{\$key} %= 31;

or

my \$href = \%hash;
&function( %\$href );

perl can make your head swim, huh?

--
DEBIAN NEWBIE TIP #3 from Will Trillich <will@serensoft.com>
:
Wondering how to FIND WHICH PACKAGE CONTAINS x-y-or-z? Just enter
"dpkg -S part/of/path" and you'll get a list of all packages that
affect paths like that. For an example, try "dpkg -S http".

Also see http://newbieDoc.sourceForge.net/ ...

```