Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to get a number from a file

Status
Not open for further replies.

xS73v3x

Programmer
Jan 31, 2003
11
US
im trying to open a file, and in it is a number i need for a for loop, but if i try to get it from the text file, for example:
$theNum = <THEFILE>;

now, $theNum will contain the number i want, and and endline! (&quot;3\n&quot;)

how can i extract just the number so i can use it in a for loop?
 
Use chop. It will strip off the last character of a string, including new line characters.

chop($theNum);
 
You could use the value in numeric context as-is, perl will convert it. Perl checks a scalar string from the left scanning for a number, stopping at the first character that would cause what's been scanned to not be a number. Examples:
Code:
&quot;1.2&quot;      => 1.2
&quot;1.2.3&quot;    => 1.2 #scanning stops at the second decimal
&quot;1b4.5&quot;    => 1 #scanning stops at the b
&quot;help!&quot;    => 0 #no numbers at start(or at all) returns zero
&quot;a123&quot;     => 0 #no numbers at start
&quot;1.2e-1&quot;   => 0.12 #support for scientific notation
&quot;1.2e-1.5&quot; => 0.12 #perl doesn't allow decimal values within scientific notation-style exponentiation
If you
Code:
use warnings;
it'll yell about arguments being non-numeric if it has to do any more converting than in the first line above.

But in general, yes, chomp your input as Cheryl advised. It's a much better way to clean up input, and a whole lot faster. ----------------------------------------------------------------------------------
...but I'm just a C man trying to see the light
 
Thanks Cheryl! chop worked great, and icrf, using it as-is doesnt work, otherwise i wouldnt have posted this :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top