
BillKSmith
Veteran
May 6, 2014, 9:41 PM
Post #4 of 6
(4507 views)
|
Re: [mixelplik] trying to parse string w/o regular expression
[In reply to]
|
Can't Post
|
|
You will never get it quite right until you specify the grammer of your input line. It probably is not exactly what you want, but the example below works for the following input grammer. The input consists of a string of ASCII characters terminated by a newline. Any character is allowed, but characters other than digits and spaces are ignored. A sequence of consecutive integers separated by one or more spaces is considered a single integer number. The sum of the integer numbers in the string is displayed.
use strict; use warnings; print "Enter test string: "; chomp( my $in = <STDIN> ); my $total = 0; my $cur_num = 0; my $last_index = length($in) - 1; for my $i (0 .. $last_index) { my $cur_char = substr $in, $i, 1; next if !grep {$cur_char eq $_} (0 .. 9,' '); if ( $cur_char eq ' ' ){ $total += $cur_num; $cur_num = 0; next; } $cur_num = 10 * $cur_num + $cur_char; } $total += $cur_num; print $total, "\n"; UPDATE: Add a more "perlish" solution.
use strict; use warnings; use IO::Prompt::Hooked; use Regexp::Common qw/number/; use List::Util qw /sum/; my $in = prompt("Enter string: "); $in =~ s/[^0-9 ]//; print sum( $in =~ /($RE{num}{int})/g ), "\n"; Good Luck, Bill
(This post was edited by BillKSmith on May 7, 2014, 6:48 AM)
|