RE: FN-FORUM: perl advice
date posted 1st June 2003 18:46
[EMAIL REMOVED] wrote:
> Hi,
> I am looking at a perl code example in a manual and I am confused...
[...]
> push @digits, (0 ..9, a .. f)[$value & 15];
[...]
> Does [$value & 15]; in the push line add another value to the list in
> digits aswell as 0 .. 9,a ..f on each while loop. In other words I am
> not sure what you end up with in @digits before it is printed. It is
> supposed to convert a decimal number to hex. I understand what $value
> & 15 does but not the square brackets or (0 ..9, a .. f).
The (0..9,a..f) constructs a set, with values
(0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f) which is then indexed by the [$value & 15]
(effectively the remainder when $value is divided by 16). It's the classic
way of converting from one base to another by using long division and
writing down the remainders - e.g.
For 1237 into base 16
1237 / 16 = 77 remainder 5 - this 5 would get mapped into (0..9,a..f) and
get pushed onto @digits as 5
77 / 16 = 4 remainder 13 - this 13 would get mapped into (0..9,a..f) and get
pushed onto @digits as d
4 / 16 = 0 remainder 4 - this 4 would get mapped into (0..9,a..f) and get
pushed onto @digits as 4
The last function merely prints out @digits in reverse order - i.e. 4d5 in
our example.
I'll leave for homework changing this to convert to any base (think about
changing the hard coded values of 15 and 16 in lines 3 and 4 of the source
code, and modifying the set as necessary)...
Cheerio!
Ross
--
[EMAIL REMOVED]
DJSE Limited, Willow End, Mawthorpe, Alford, Lincolnshire, LN13 9LT
T: 01507 466 797
F: 01507 463 731
M: 07970 801 661
http://www.djse-ltd.co.uk