Home  |  Linux  | Mysql  | PHP  | XML
From:John W. Krahn Date:Fri Feb  5 11:46:35 2010
Subject:Re: 1-line text file with numbers, need to add to them
Frank wrote:
> On Feb 4, 4:35 pm, jwkr...@shaw.ca ("John W. Krahn") wrote:
>> Chris wrote:
>>> I need some help with this problem.
>>> I've got a text file datafile with 1 line of data comprised of 30
>>> different numbers delimited with ~s.
>>> I need to open this file, grab this line of data, split it into
>>> individual numbers, perform some simple math (addition) on each
>>> number, and then put the new values back into the datafile, replacing
>>> the original data that was there.
>> perl -i.bak -pe's/(\d+)/ $1 + 3 /eg' yourdatafile
>>
>> John
>> --
>> The programmer is fighting against the two most
>> destructive forces in the universe: entropy and
>> human stupidity. -- Damian Conway

Please don't quote sigs when you reply.


> For instance, the below is your data file--- data.txt.

I'm sorry, I don't have a data file.

> 12~s1~s314~s5677~s899~s0~s
> Here is the codes:
> #!/usr/bin/perl

You should include the warnings and strict pragmas so that perl can help
you find mistakes:

use warnings;
use strict;

> open(DATA,"data.txt");

You should *always* verify that the file opened correctly before trying
to use a possibly invalid filehandle:

open FH, '<', 'data.txt' or die "Cannot open 'data.txt' $!";

> while(<DATA>) {
> $number=$_;

That is usually written as:

while ( my $number = <FH> ) {

But why are you calling a line of input text "number"?

> # print $number;
> while ($number =~ /([0-9]+)~s/g){
> printf ("%d\n","$1");

Why are you copying $1 to a string before having printf() convert it to
a string? Why use printf() when print() would be better and simpler:

print "$1\n";

> }
> }
> close(DATA);



John
--
The programmer is fighting against the two most
destructive forces in the universe: entropy and
human stupidity. -- Damian Conway
Navigate in group perl.beginners at sever nntp.perl.org
Previous Next


Your recent visits
Re: 1-line text file with numbers, need to add to them
Re: 1-line datafile, need data for another routine
LMPX.COM :: Linux, Mysql, Php, Xml
no lstat happens
New on http://perl-begin.org/ - more topical pages and pages for Perl uses



  
© No Copyright
You are free to use Anything, but please consult your advocate before doing so as this website
also list content from other sources which may be copyrighted.
Site Maintained by Zareef Ahmed
Powered By PHP Consultants