perl,decimal , compare two decimal values with specific range in perl


compare two decimal values with specific range in perl

Question:

Tag: perl,decimal

I am new to Perl. I have two different sets of arrays. Those two arrays having decimal values, both does not have an exact matches, it might be differ only either +0.5 or -0.5. I tried this program, it's not working.

@inpt = qw(1003.3965 1036.4392 1037.3843 1045.4459 1101.4259 1107.4253 1118.3928 1191.4904 1320.4855 1420.6291 1440.6921 1562.6698 1742.7587 2084.9137 2248.8761 2337.8865 2628.9931);
@outpt = qw(1191.6017 1101.5336 2629.2865 1742.9336 1036.5726 2338.1574 2249.1057 1440.8222 1440.2074);

foreach $s (@outpt){

    $inc = $s + 0.5;
    $dec = $s - 0.5;

   foreach $p ( @inpt ) {
        if ( $p .. $inc ) {           
            print "$p \t $inc";
        }
        elsif ( $p .. $dec ) {
            print "$p \t $dec";
        }
    }
}

I expected the below output. The @outpt value of 1191.6017 is matching with the range of +0.5 or -0.5 in @inpt value of 1191.4904.

outpt          inpt
1191.6017     1191.4904
1101.5336     1101.4259
2629.2865     2628.9931
1742.9336     1742.7587
1036.5726     1037.3843
2338.1574     2337.8865
2249.1057     2248.8761
1440.8222     1440.6291
1440.2074     1440.6291

Answer:

try this:

use strict;
use warnings;

my $limit = 0.5;
my $result = "";

my @inpt = qw(1003.3965 1036.4392 1037.3843 1045.4459 1101.4259 1107.4253 1118.3928 1191.4904 1320.4855 1420.6291 1440.6921 1562.6698 1742.7587 2084.9137 2248.8761 2337.8865 2628.9931);
my @outpt = qw(1191.6017 1101.5336 2629.2865 1742.9336 1036.5726 2338.1574 2249.1057 1440.8222 1440.2074);

foreach my $s (@outpt){
   foreach my $t (@inpt) {
      if($s >= $t - $limit && $s <= $t + $limit) {
          $result .= "$s \t $t\n";
      }
   }
}     
print $result;

Related:


Perl & Regex within Windows CMD Line


regex,windows,perl
Is there anyway to accomplish matching + storing all in one cmd line? So instead of saving the matches to an array: i.e. ($matches) = $filecontents =~ m/.../g ...the matches would save to a *.txt file? I have been experimenting for a couple of days now, and believe that I...

Why Filter::Indent::HereDoc complain when blank line in middle of HereDoc


perl,heredoc
I am trying Filter::Indent::HereDoc which allows one to indent the HereDocument. This is very useful, to be able to have HereDoc that flows with the code logic. From the above link When a 'here document' is used, the document text and the termination string must be flush with the left...

Deleting upto a line


bash,perl,shell,sed,scripting
I have a line that looks like: foo cat dog = -48.34277635 foo(horse->0) = -60.34277635 and I only want the last set of numbers: -60.34277635 The line is formatted with that exact spacing. I've looked everywhere for a simpler solution, but I can't find anything without chopping the file piece...

Perl: Multiply loops, 1 hash and regex


arrays,regex,perl,hash,perl-data-structures
I got stuck with logic behind loops (while & foreach) and AoH. I have basic knowledge about loops and arrays of hashes, but I can't quite understand how to combine them into 1 single and simple solution. My task is to check regular user's password age, if it is older...

Command line arguments in Perl


perl
I am working on an open source project for GSoC and I have this piece of Perl code with me. I need to create another Perl file for a similar task. However, I am having trouble understanding 3 lines of this file. More specifically, I am not able to understand...

Windows/Linux child process STDIN differences


linux,windows,perl,process,stdin
I built a simple text processing script at work to be used by another program. When I was done, someone remembered that the script needs to not block STDIN/STDOUT for the tool using it to work right, and modified the script accordingly. The script opens *nix's cat in a subprocess...

Counting occurrences of a word in a string in Perl


regex,perl
I am trying to find out the number of occurrences of "The/the". Below is the code I tried" print ("Enter the String.\n"); $inputline = <STDIN>; chop($inputline); $regex="\[Tt\]he"; if($inputline ne "") { @splitarr= split(/$regex/,$inputline); } [email protected]; print $scalar; The string is : Hello the how are you the wanna work on...

Can't locate module(s) using Mojo::DOM


perl,dom,mojolicious,mojo
I'm new to Mojolicious. I am sure this is probably a setup problem, but it's eaten up an entire day of my time. I'm trying to run this simple test code #!/usr/bin/perl use strict; use warnings; use Mojo::DOM; use Mojo::UserAgent; my $ua = Mojo::UserAgent->new(); $ua->get('http://stackoverflow.com/questions/26353298/find-links-containing-bold-text-using-wwwmechanize')->res->dom('a div')->ancestors('div.spacer')->each( sub { say $_->all_text...

Difficulties initializing an array in Perl


arrays,perl,hash
I have the following code: print Dumper($dec_res->{repositories}[0]); print Dumper($dec_res->{repositories}[1]); my @repos = ($dec_res->{repositories}); print scalar @repos . "\n"; and the output is the following: $VAR1 = { 'status' => 'OK', 'name' => 'apir', 'svnUrl' => 'https://url.whatever/svn/apir', 'id' => 39, 'viewvcUrl' => 'https://url.whatever/viewvc/apir/' }; $VAR1 = { 'status' => 'OK', 'name'...

Perl Debugging Using Flags


perl,debugging,script-debugging
So my goal is to find an easy way to turn on print statements in Perl a flag. In C/C++ you can use a #define to choose if certain code is run and it is a way to turn on and off debug print statements. Where if a #define DEBUG...

Create unicode character with pack


perl,unicode
I am trying to understand how Perl handles unicode. use feature qw(say); use strict; use warnings; use Encode qw(encode); say unpack "H*", pack("U", 0xff); say unpack "H*", encode( 'UTF-8', chr 0xff ); Output: ff c3bf Why do I get ff and not c3bf when using pack ?...

Get ISO DateTime with only core modules in Perl?


perl
I would like to get a date-time string such as 2015-06-17 10:20:34 with only core modules. The reason of this is that cpan install DateTime takes ages on my machine because of the tests and the fetch of all the dependencies. If I give my Program to my colleagues. They...

Taking multiple header (rows matching condition) and convert into a column


bash,perl,command-line,awk,sed
Hello I have a file that has multiple Headers in it that I need to have turned into column values. The file looks like this: Day1 1,Smith,London 2,Bruce,Seattle 5,Will,Dallas Day2 1,Mike,Frisco 4,James,LA I would like the file to end up looking like this: Day1,1,Smith,London Day1,2,Bruce,Seattle Day1,5,Will,Dallas Day2,1,Mike,Frisco Day2,4,James,LA The file...

Find numbers in a file and change their value with perl


regex,perl
I have a file with some data in it but there are a bunch of annoying numbers that are less than one which I wanted to just change to 1 instead of manually doing it. I was wondering how you would do this in perl. I tried using something like...

Plain text emails displayed as attachment on some email clients


perl,email,attachment,mime,plaintext
The email can be viewed normally using some email clients (Evolution, Thunderbird), but with other clients (e.g., GMX) the body of the message remains empty and an attachment containing the body of the message is sent. I would like to know how I can prevent this from happening, since the...

Creating a sequence of unique random digits


arrays,perl,foreach,unique
I have the following code use strict; use warnings; use 5.22.0; # Generating random seed using # Programming Perl p. 955 srand( time() ^ ($$ + ($$ << 15 ) ) ); # Generating code that could have duplicates my @code = ( (int(rand(9)) + 1), (int(rand(9)) + 1), (int(rand(9))...

Check for decimal point and add it at the end if its not there using awk/perl


regex,perl,shell,awk
I have test.dat file with values given below: 20150202,abc,,,,3625.300000,,,,,-5,,,,,,,,,,,,,,,,,,,,,, 20150202,def,,,,32.585,,,,,0,,,,,,,,,,,,,,,,,,,,,, 20150202,xyz,,,,12,,,,,0.004167,,,,,,,,,,,,,,,,,,,,,, My expected output is shown below: 20150202,abc,,,,3625.300000,,,,,-5.,,,,,,,,,,,,,,,,,,,,,, ^. added here 20150202,def,,,,32.585,,,,,0.,,,,,,,,,,,,,,,,,,,,,, ^. added here 20150202,xyz,,,,12.,,,,,0.004167,,,,,,,,,,,,,,,,,,,,,, ^. added here So if column 6 and 11 doesn't have decimal point in it, then we should add '.' at the end of...

How to copy matches from an extremely large file if it contains no newlines?


python,linux,bash,perl,grep
The problem is I cannot avoid working with extremely big files which contain no newlines in them: <a>text1</a>...gigabytes of data here, all in one single line...[a text to extract b> What should I do if I want to copy matches from this file (putting every match in a separate line,...

Regex in Perl Uninitialized $1


regex,perl
My string looks like this: <File `../Path/To/My_File.gif'> I want to extract just "Path/To/My_File.gif". Here is the check I have: if ($row =~ /(?<=File `..\/).*(?=')/) { print "Found it!\n"; print "$1\n"; } I see "Found it!" printed to the console but also get an error saying that $1 is uninitialized. What...

What does this horribly ugly (yet somehow secretly beautiful) Perl code do?


perl,formatting,deobfuscation
I found this code in a Powerpoint presentation about Perl scripting and this was on a page demonstrating how ugly Perl code can get if you really wanted to make it that way. The presentation says nothing about what this code does. Honestly I am just very curious to know......

Perl: Static vs Package methods


perl,static,package
I need to create a package which will be used by other developers. What is the best way to implement static methods? For static (class) methods I must expect 1st parameter $class, and method must be called as a class method: My::Package->Sub1(); From the other hand I can write a...

Reading from DATA file handle


performance,perl
My perl module needs to use a look up table that's about 309,000 lines long. Currently the part that loads the table into an array looks (roughly) like this: use strict; use warnings; # load all the data from below my @ref_data; while (<DATA>) { push @ref_data, $_ } close...

Perl XML-RPC output format/schema


php,xml,perl,rpc,xml-rpc
I'm writing a script in Perl to use two XML-RPC APIs. With one of them it works fine, with the other one i always get an empty result. After contacting the vendor of the second API, they sent me a PHP sample script to operate with the API. I couldn't...

Perl : Display perl variable awk sed echo


perl
When I am using below command directly its working fine but when I am trying to put this in perl script its giving lots of error. my $calculate = `echo "$value" | awk -F "SP=" '{print $2}' | awk -F ";" '{print $1}' | awk -F ":" '{print $2}' |...

Why this exclusion not working for long sentences?


text-processing,perl
Command perl -ne 'print unless /.[240,]/' input.txt > output.txt which includes some sentences which are longer than 240 letters. Why? Example data Development of World Funny Society program on young people who are working hard for the sport and social life such that they have time to go pizzeria every...

Can someone help me explain this code that is converting decimal fractions into a binary?


python,while-loop,binary,floating-point,decimal
Can someone help me explain this code that is converting decimal fractions into a binary? Convert the decimal fractions into a binary form: x = float(raw_input('Enter a decimal number between 0 and 1: ')) p = 0 while ((2**p)*x)%1 != 0: print('Remainder = ' + str((2**p)*x - int((2**p)*x))) p +=...

Why does my value change when I am not resetting it?


perl,reference
I have the following example exhibiting the problem I'm struggling to resolve. In the toy example, I have an array @actors with two levels. I also have an array of hashes @people which I am using to 'look up' properties of the people in @actors. The output of the program...

Regex to match ASCII Table character with decimal value


regex,decimal,ascii
So I need a Regex to match the ASCII character STX(Start Of Text) which is number 2 on ASCII Table. I tried ^ as Regex101.com suggest for start of text but it was unsuccessful. Then I tried [[:ascii:]] which was matching for all ASCII characters. Is there any way to...

Multiplying 2 decimal values resulting wrong number [closed]


php,mysql,decimal,multiplying
I'm sure I'm missing something here. Take a look: On my MySQL database, the 'value' field is a decimal, like this: My database enconding is: utf8_general_ci. My PHP code, to show the values: $sale_limit_gen = Coo::getSaleLimitById(1); $sale_limit_ale = Coo::getSaleLimitById(2); echo $sale_limit_gen['value']; echo '<br>'; echo $sale_limit_ale['value']; echo '<br>'; echo $sale_limit_ale['value'] *...

C++ - back to start of loop without checking the condition


c++,perl,loops,redo
Programming on perl, we can use a smart function named 'redo' - we can go back to the start of the loop, without looking at the condition. It's useful when, for example, we create a table in which we must to set a expected values/characters (e.g. "a-b-c", nothing else). I...

problems copying shared hash in perl threads


multithreading,perl
I encountered what I feel is strange behavior of shared hash in perl and needed some help understanding it. The actual problem is in a far larger code-base and I have tried reducing it to smaller reproducible script. So essentially the problem I'm facing is I have a shared variable...

Print all non-matching items in Perl


regex,perl,if-statement,matching
I have a perl script that compares text from two files. The files on most days should be exactly the same, but if for some reason some of the text in the file changes I want the script to print out all the text that is not exactly the same...

Looping variables


perl,scripting
I'm working with perl to make a script that will work with Dot products/assorted vector math. I've got a working script ( Still very much in progress/needs refinement ) that will do what I ask. #!/usr/bin/perl use strict; use warnings; use diagnostics; use Math::Vector::Real; use 5.010; use Math::Trig; my $source...

calling cgi script from other cgi script


perl,cgi
I found a puzzling behavior using perl cgi for which -- I guess -- there is a perfectly valid explanation but I couldn't find one. There is this question on stackoverflow, but what it describes seems to fail for me. The situation: I have two perl cgi scripts. One of...

What happens to a non-matching regex in a Perl subroutine call?


perl
I'm trying to make sense of what's happening with a non-matching regex in a subroutine call. Consider this script: sub routine{ print Dumper(\@_); } my $s = 'abc123'; # These pass a single element to &routine &routine( $s =~ /c/ ); # 1. passes (1) &routine(2 == 3); # 2....

Reducing code verbosity and efficiency


perl
I came across the below where some heavy stipulations were done, finally we got a number of @hits and we need to return just one: if ($#hits > 0) { my $highestScore = 0; my $chosenMatch = ""; for $hit (@hits) { my $currScore = 0; foreach $k (keys %{$hit})...

Perl would I use fc over uc?


perl
When would you ever need to use fc(), when would uc() ever fail? Perl fc documentation...

unable to understand qr interpolation


regex,perl
I was reading Programming Perl where I learned qr interpolation of strings as regex as : $re = qr/my.STRING/is; print $re; # prints (?si-xm:my.STRING) and it says The /s and /i modifiers were enabled in the pattern because they were supplied to qr//. The /x and /m, however, are disabled...

-M Script start time minus file modification time, in days


perl,perldoc
I would expect -M $_ to be negative, but it is zero for: perl -E 'qx(touch $_), sleep(5), say -M for "/tmp/file"' Does perldoc mentions such behavior?...

Version-dependent fallback code


perl
I have a script that needs to run on multiple servers, however, each server may not have the same version of Perl available and may have differing features. Perl v5.14 introduced the /r modifier for regular expressions which returns the result of a substitution and leaves the original text alone....

How to pass a hash as optional argument to -M in command line


perl,hash,package,command-line-interface
I know that when we need to pass some arguments to the use keyword after a package name we can pass them in the command line after the -M parameter. For example: use feature 'say'; say 'hello!'; can be invoked from the command line with >perl -Mfeature=say -e"say 'hello!'" But...

How to match and remove the content preceding it from a file in unix [closed]


mysql,perl,sed,solaris
I have a mysql dump file, and i want to remove the content of the file after "-- Final view structure for view view_oss_user" using sed/perl. The input file is something like this : Content : rom `target` */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results...

how to print all the lines of a text file from hash - perl


perl
I am reading a text file which is having multiple lines in it. I have been assigned a task to print the lines using hash. "\n" is the delimiter we can use. Here is what I tried and got stuck : code : use strict; use warnings; my %hash =...

Conversion from char to int and printing the decimal value


c,char,printf,decimal,ascii
char str[20]; printf("Enter anything\n"); scanf("%s",str); for(int i = 0 ; i<strlen(str) ; i++) { if( isdigit(str[i])) printf("%d",(int)str[i]); } I tried with the above code but the output is in ASCII values of the numbers rather then actual numbers. Like , input: "0" output: "48". When I try (int)(str[i]-'0'); instead of...

Capture tee's argument inside piped Perl execution


perl,unix
How to capture piped command's argument ? I use : perl my_script.pl -some_args | tee arg_filename How to get arg_filename 's value inside my_script.pl ? CONTEXT I need to send this filename in a mail which my_script.pl sends at the end. I need to use tee because we dump huge...

Perl: Using Text::CSV to print AoH


arrays,perl,csv
I have an array of hashes (AoH) which looks like this: $VAR1 = [ { 'Unit' => 'M', 'Size' => '321', 'User' => 'test' } { 'Unit' => 'M' 'Size' => '0.24' 'User' => 'test1' } ... ]; How do I write my AoH to a CSV file with separators,...

Opening multiple files in perl array


arrays,perl
I have a perl script where by I assigned all the files with a .log extension to an array called @allfiles. How do I run my script for the files stored in each array? My idea is something like open(my $fn, '<', @allfiles) or die "Could not open file '@files':...

How to extract some text from an HTML doc using Web::Query


perl
I'm trying to extract the subject (between the h3 tags) in the following example using Web::Query. Find 'h3' returns the author text, but I want the h3 in the subject class instead. I tried .subject.div.h3 but it returns undef. #!/usr/bin/perl use strict; use warnings; use Web::Query; # libweb-query-perl use Data::Dumper;...

How to tell Perl to always run with use v5.010?


perl
When I write small programs or oneliners I cannot use say. I always need to put: #!/usr/bin/env perl use strict; use warnings; use 5.010; In oneliners I can simply do perl -E "say 'toto'" but in regular programs I don't know how to do it... Any idea?...

Perl - an array content


arrays,perl
Can you explain me how to check if an element belongs to array? My script needs to know whether the element has wanted extension to make a shortcut and copy it to another directory. Here is an example: my @array = qw(avi mp4 mov); my $dir = "E:\Downloads"; opendir (my...