Multiplying floats and ints in perl through an if statement - perl

My goal is to utilize perl to multiply a float and an int, I have got this far and am still researching, many thanks to any help.
#!/usr/bin/perl
$float1 = 0.90
print "give me an integer";
$that_integer = <>;
if ($that_integer<=5000) {
print "$that_integer * $float1";
}

Welcome to Perl. A few tips:
Always include use strict; and use warnings; at the top of EVERY Perl script.
chomp your input from <STDIN> to remove the newline at the end.
You can't interpolate expressions. However, you can easily include them in a string easily using printf.
As demonstrated:
#!/usr/bin/perl
use strict;
use warnings;
my $float1 = 0.90;
print "give me an integer: ";
chomp( my $that_integer = <> );
if ( $that_integer <= 5000 ) {
printf "%f\n", $that_integer * $float1;
}

Arbitrary expressions can't be interpolated into double-quotes. Try:
print $that_integer * $float1, "\n";
The perlop documentation page includes all the gory details of parsing quoted constructs.

Related

How to convert string into equation and solve it in Perl? [duplicate]

If one string is expressed like below
$str = "5+2-1";
I'd like to get the calculation result from that string.
How do I convert to scalar to compute this?
Thanks.
The easiest way to do this:
print eval('5+2-1');
but it's not safe:
print eval('print "You are hacked"');
You need to check string before eval it.
Also you can use Math::Expression module or many other modules from cpan:
#!/usr/bin/perl
use strict;
use warnings;
use Math::Expression;
my $env = Math::Expression->new;
my $res = $env->Parse( '5+2-1' );
# my $res = $env->Parse( 'print you are hacked' ); # no math expression here
print $env->Eval( $res );
If you are sure the string does not contain any malicious code you can use eval to treat the content of it as perl code.
#!/usr/bin/perl
use strict;
use warnings;
my $string = "5+2-1";
print eval($string);
#print 6

How can I force the user to enter an integer?

I want to check that the input from the user is an integer number. I tried the following, but it doesn't work:
try {
print "Enter int";
$num=int(<>);
print "okej";
}
catch (ValueError $e{
print"not int";
}
You really do not want to punish users for leading/trailing spaces (as too many web sites these days seem to be doing), but also avoid leading zeros. Also, make sure the output is flushed before asking for input:
#!/usr/bin/env perl
use strict;
use warnings;
my $input;
until (defined $input) {
local $| = 1;
print 'Enter an integer: ';
($input) = (<STDIN> =~ /\A \s* (-? [1-9] [0-9]* ) \s* \z/x);
}
print "$input\n";
The int function does not check if something is an integer. Instead, it converts its argument to an integer. So, int(1) is 1, int(1.11) is also 1, and int('a') is 0 — with a warning if you enabled warnings.
See also:
"How do I determine whether a scalar is a number/whole/integer/float?" in perlfaq4. You should read the excellent documentation that comes with Perl.
perldoc -v '$|'
Check to see if input has only digits and nothing else...
use warnings;
use strict;
print "Enter integer: ";
my $input = <>;
chomp $input;
print "is int\n" if $input =~ /^[0-9]+$/;

Trying to find the index of the first number in a string using perl

I'm trying to find the index of the first occurrence of a number from 0-9.
Let's say that:
$myString = "ABDFSASF9fjdkasljfdkl1"
I want to find the position where 9 is.
I've tried this:
print index($myString,[0-9]);
And:
print index($myString,\d);
Use regex Positional Information:
use strict;
use warnings;
my $myString = "ABDFSASF9fjdkasljfdkl1";
if ($myString =~ /\d/) {
print $-[0];
}
Outputs:
8
You can try even below perl code:
use strict;
use warnings;
my $String = "ABDFSASF9fjdkasljfdkl11";
if($String =~ /(\d)/)
{
print "Prematch string of first number $1 is $`\n";
print "Index of first number $1 is " . length($`);
}
You can try this:
perl -e '$string="ABDFSASF9fjdkasljfdkl1";#array=split(//,$string);for $i (0..$#array) {if($array[$i]=~/\d/){print $i;last;}}'

How to print in decimal form rather than exponential form in perl

I have written a program in perl.My requirement is to print the only the decimal numbers, not exponential numbers. Could you please let me know how to implement this ?
My program is calculating the expression 1/2 power(n) , where n can take up integer numbers from 1 to 200 only. And only 100 lines should be printed.
Example:
N=1, print 0.5
N=2, print 0.25
My program looks like:
#!/usr/bin/perl
use strict;
use warnings;
my $exp;
my $num;
my $count_lines = 0;
while($exp = <>)
{
next if($exp =~ m/^$/);
if($exp > 0 and $exp <=200 and $count_lines < 100)
{
$num = 1/(2 ** $exp);
print $num,"\n";
$count_lines++;
}
}
Input values:
If N = 100 , then out is getting printed in exponential form. But, the requirement is it should get printed in decimal form.
A simple print will pick the "best" format to display the value, so it chooses scientific format for very large or very small numberss to avoid printing a long string of zeroes.
But you can use printf (the format specifiers are documented here) to format a number however you want.
0.5200 is a very small number, so you need around 80 decimal places
use strict;
use warnings;
while (my $exp = <>) {
next unless $exp =~ /\S/;
my $count_lines = 0;
if ($exp > 0 and $exp <= 200 and $count_lines < 100) {
my $num = 1 / (2 ** $exp);
printf "%.80f\n", $num;
$count_lines++;
}
}
output for 100
0.00000000000000000000000000000078886090522101181000000000000000000000000000000000
and for 200
0.00000000000000000000000000000000000000000000000000000000000062230152778611417000
If you would like to remove insignificant trailing zeroes then you can use sprintf to put the formatted number into a variable and then use s/// to delete trailing zeroes, like this
my $number = sprintf "%.80f", $num;
$number =~ s/0+$//;
print $number, "\n";
which gives
0.00000000000000000000000000000078886090522101181
and
0.00000000000000000000000000000000000000000000000000000000000062230152778611417
Note that the true value of the calculation has many more digits than this, and the accuracy of the result is limited by the size of the floating point values that your computer uses.
0.5 ^ 200 is too small for a double floating point number, you need to use Math::BigFloat, that will overload basic math operations and output operators such as print for you, for example:
#!/usr/bin/perl
use strict;
use warnings;
use Math::BigFloat;
my $x = Math::BigFloat->new('0.5');
my $y = Math::BigFloat->new('200');
print $x ** $y, "\n";
Or use bignum:
#!/usr/bin/perl
use strict;
use warnings;
use bignum;
print 0.5 ** 200, "\n";
Output:
$ perl t.pl
0.00000000000000000000000000000000000000000000000000000000000062230152778611417071440640537801242405902521687211671331011166147896988340353834411839448231257136169569665895551224821247160434722900390625
You can use printf or sprintf to specify the format of what you want to print out.
#!/usr/bin/perl
use strict;
use warnings;
my $num = 0.000000123;
printf("%.50", $num)
If you need something like Perl 5 formats, take a look at Perl6::Form (note, this is a Perl 5 module, it just implements the proposed Perl 6 version of formats).

Parse scientific integer representation in perl

What is the most elegant way to parse an integer given in scientific representation, i.e. I have an input file with lines like
value=1.04738e+06
Sure I can match the all the components (leading digit, decimal positions, exponent) and calculate the result, but it seems to me there is a more straight-forward way.
% perl -e 'print "1.04738e+06" + 0'
1047380
You just need to coerce it to a number and Perl will DWIM.
FYI: looks_like_number() from Scalar::Util might come in handy.
#!/usr/bin/env perl
use strict;
use warnings;
use Scalar::Util qw( looks_like_number );
my $line = "value=1.04738e+06";
my ( $tag, $value ) = split /\s*=\s*/, $line, 2;
if( looks_like_number( $value ) ){
$value = 0 + $value;
}
print "$tag=$value\n";