fasoli has asked for the wisdom of the Perl Monks concerning the following question:
Hi Wise Monks!
I've been really confused about a problem I'm having with a file. It's a text file, with 4 columns, and with a few thousand lines. The contents are numbers that look like this
1.234 5.6789 -1.235Those files occur as outputs from a software. The problem is that in some cases the contents look like this
1.234 5.6789-12.235*notice the number of the last column: because now there are 2 numbers before the decimal point, the number gets stuck on the second column.
Naturally now I'm having trouble plotting this file. So I'm trying to match strings where there is a digit, followed by a hyphen, followed by another digit, and then I want to replace this -hopefully correctly- with an added whitespace so that the numbers are correct.
I'm trying this and the regex match works, it does print the problematic bits:.
#!/usr/bin/perl use warnings; use strict; my $test; open my $INPUT, '<', "file.txt" or die $!; while (<$INPUT>) { chomp $_; if ($_=~/(\d)(-)(\d)/) { print "$1$2$3 \n"; } }
But now I'm stuck: how do I complete the replace action? And how do I print the new contents of the file? I haven't succeeded in anything more than compilation errors. In terms of replacing, I've tried this
if ($_=~s/(\d)(-)(\d)/(\d) (-)(\d)/) {(supposedly telling the script to add spaces between the digit before the hyphen and the hyphen itself)
but I get this error
Unrecognized escape \d passed throughThen I tried it with the $1$2$3 but again it was wrong. Can you give me any hints about how to make the replace function work?? Thank you so much!
|
|---|