Gossamer Forum
Home : General : Perl Programming :

Correct to an integer?

Quote Reply
Correct to an integer?
Here is the file content of 123.txt:
--------------------------------------
123][456][987][
--------------------------------------
And this is the perl file:
--------------------------------------
#!/usr/local/bin/perl
open(MARK, "123.txt");
$MARK = <MARK>;
close(MARK);
($a, $b, $c) = split(/][/, $MARK);
$ABC = $b + $c / $a
--------------------------------------
Then... $ABC should be 12.0975XXXXX
Now I dont want .0975XXXXX, I only want an integer - 12 for $ABC. What will the perl code be???
(I have learn perl language for only 6 days, so if there is any other problem can you tell me???)
Thanks a lot!!!
Quote Reply
Re: Correct to an integer? In reply to
Well, what you posted doesn't compile. You need to escape the [ and ] in your split reg expression like:

split(/\]\[/, $MARK);

To make $ABC an integer, just do:

$ABC = int ( $ABC );

which will take the floor (just cut off the decimal places). To round try:

$ABC = int ( $ABC + 0.5 );

Hope that helps,

Alex
Quote Reply
Re: Correct to an integer? In reply to
Just a note.. PERL doesn't care if your number is a string or a integer, it will figure out what you want them to do depending on the context you place them in.

As an example. Lets say we have two numbers:

$a = 123;
$b = 456;

If we perform an addition the following, our answers just come out the way we think they should:

print $a + $b; # This is 579
print $a . $b; # This is 123456

PERL doesn't care if you declare variables, and even when you do, you only declare the type of variable (scalar, array, hash or typeglob). There is no difference between the content of the variable to PERL.

Now, if you had a real number like 1.234 and you wanted to convert to a decimal, you could easily round or clip of that part with other Perl functions.

Just off hand, your split match is really fragged, using ][ as a column separator in your file is bound to cause headaches galore for you and your code. If you insist on using that separator, you would have to do this with your split:

split /\]\[/, $MARK;

Why? Because our pattern matching uses brackets [] as a reserved symbol, so you must escape them.

Hope this helps


------------------
Fred Hirsch
Web Consultant & Programmer

[This message has been edited by fhirsch (edited January 06, 1999).]
Quote Reply
Re: Correct to an integer? In reply to
    
Quote:
$ABC = $b + $c / $a

Also, the above may not return what is expected.

As written, $c would be divided by $a before it adds $b to $c and is essentially equivalent to:

Quote:
$ABC = $b + ($c / $a)

If you want $b to be added to $c before it is divided by $a, you should write that as:

Quote:
$ABC = ($b + $c) / $a

Just a thought.

------------------
Bob Connors
bobsie@orphanage.com
www.orphanage.com/goodstuff/
goodstufflists.home.ml.org/


[This message has been edited by Bobsie (edited January 06, 1999).]