Home: Perl Programming Help: Regular Expressions:
parsing a line of numbers



piper68
Novice

Mar 14, 2010, 10:57 AM


Views: 9800
parsing a line of numbers

I have a file with the contents of this....

UTC 15 16 17 18 19 20 21 22 23 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15

what i would like to do is parse each set of numbers with a comma and each on a new line so like this...

15,
16,
17,
18,
19,
20,
21,
22,
23,
00,
01,
02,
03,
04,
05,
06,
07,
08,
09,
10,
11,
12,
13,
14,
15,

i'm trying to learn perl so any help on this would be greatly appreciated.

thanks


FishMonger
Veteran / Moderator

Mar 14, 2010, 12:43 PM


Views: 9797
Re: [piper68] parsing a line of numbers

What have you tried?


piper68
Novice

Mar 14, 2010, 1:06 PM


Views: 9795
Re: [FishMonger] parsing a line of numbers

I've tried this and works but is there a way to write this more simple? thanks.

perl -pe '/UTC[\s]+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/;$_=($1)?"$1,\n$2,\n$3,\n$4,\n$5,\n$6,\n$7,\n$8,\n$9,\n$10,\n$11,\n$12,\n$13,\n$14,\n$15,\n$16,\n$17,\n$18,\n$19,\n$20,\n$21,\n$22,\n$23,\n$24,":""' $TXT_PATH/a.txt > $TXT_PATH/b.txt


(This post was edited by piper68 on Mar 14, 2010, 1:07 PM)


FishMonger
Veteran / Moderator

Mar 14, 2010, 1:31 PM


Views: 9791
Re: [piper68] parsing a line of numbers


Code
perl -ane 'for(@F){print "$_,\n" unless /\D/}' a.txt



murugaperumal
Novice


Mar 14, 2010, 10:49 PM


Views: 9784
Re: [piper68] parsing a line of numbers

Use the following code

Code
my $var="UTC 15 16 17 18 19 20 21 22 23 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 "; 
my @array;
@array=split(" ",$var);
foreach(@array)
{
if(/\d+/)
{
print "$_,\n";
}
}



(This post was edited by murugaperumal on Mar 14, 2010, 10:49 PM)


shawnhcorey
Enthusiast


Mar 15, 2010, 7:19 AM


Views: 9759
Re: [piper68] parsing a line of numbers

Try:

Code
#!/usr/bin/perl 

use strict;
use warnings;

while( <DATA> ){
my @captured = m{ (\d+) }gmsx;
print join( ",\n", @captured ), ",\n";
}

__DATA__
UTC 15 16 17 18 19 20 21 22 23 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15


__END__

I love Perl; it's the only language where you can bless your thingy.

Perl documentation is available at perldoc.perl.org. The list of standard modules and pragmatics is available in perlmodlib.

Get Markup Help. Please note the markup tag of "code".


roolic
User

Mar 22, 2010, 11:05 PM


Views: 9579
Re: [piper68] parsing a line of numbers

using the regular expression:


Code
my $str = "UTC 15 16 17 18 19 20 21 22 23 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15"; 

# first remove non-digital symbols from the line start
$str =~ s/^\D+//;

# actually reformat
$str =~ s/(\d+)\D*/$1,\n/g;

print $str;