Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: quick way to add value of a hash with same x, y, z?

by QM (Parson)
on Aug 10, 2017 at 10:32 UTC ( [id://1197148]=note: print w/replies, xml ) Need Help??


in reply to quick way to add value of a hash with same x, y, z?

OK, I knocked this up quick, but it's untested.

You didn't say what should happen if a coord triple is only in one file. And probably needs a lot of safety checks, if these are big files.

#!/usr/bin/env perl # Store X,Y,Z coordinates from one file, along with a number and press +ure. # Find a matching coord in a second file, subtract pressure1 from pres +sure2. # Output with the number from the first file. # Sample data: # 0, 4.38336420e+00, -2.47429684e-01, 6.79128885e+00, 1.51447906e+05 # 1, 4.38336420e+00, -2.78662264e-01, 6.79128885e+00, 1.58727812e+05 # 2, 4.38336420e+00, -2.78662264e-01, 6.69878864e+00, 1.61132406e+05 # 3, 4.38336420e+00, -2.47429684e-01, 6.69878864e+00, 1.54500719e+05 # Assume there are 2 filenames on the command line, in the correct ord +er. use strict; use warnings; our $key_format = '%16.8f'; # Fixed decimals for use in keys our $out_format = '%e'; # scientific notation sub read_it { my $line = shift; chomp($line); my ($n, $x, $y, $z, $p) = split /,\s+/, $line; my $key = sprintf "$key_format,$key_format,$key_format", $x, $y, $ +z; return($n, $x, $y, $z, $key, $p); } our %press; # File 1 while (<>) { my ($n, $x, $y, $z, $key, $p) = read_it($_); $press{$key}{num} = $n; $press{$key}{press} = $p; } continue { # If this is the end of the first file, close it and escape the lo +op if (eof) { # "eof", not "eof()"! close ARGV; last; } } # File 2 while (<>) { my ($n, $x, $y, $z, $key, $p2) = read_it($_); if (exists($press{$key})) { my $pdiff = $p2 - $press{$key}{press}; my $n1 = $press{$key}{n}; print "%d, $out_format, $out_format, $out_format, $out_format\ +n", $n1, $x, $y, $z, $pdiff; } } exit;

-QM
--
Quantum Mechanics: The dreams stuff is made of

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1197148]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (8)
As of 2024-04-19 08:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found