http://www.perlmonks.org?node_id=1002071


in reply to Why is the List upload with STDIN from a text file giving wrong result for mean?

choroba has presented an approach using split and some post-processing of the resultant sub-strings. Here is a regex-based 'extractive' approach that goes after the digits of interest directly and may make it easier to deal with 'messy' strings. See perlre, perlrequick, perlretut.

>perl -wMstrict -le "my $string = qq{(10 ,12, 14 , 16,18)\n}; print qq{string is [[$string]]}; ;; my @array = $string =~ m{ \d+ }xmsg; printf qq{array (@array) has %d elements \n}, scalar @array; ;; my $sum = 0; $sum += $_ for @array; print qq{sum of array is $sum}; ;; my $mean = $sum / @array; print qq{mean of array is $mean}; " string is [[(10 ,12, 14 , 16,18) ]] array (10 12 14 16 18) has 5 elements sum of array is 70 mean of array is 14
  • Comment on Re: Why is the List upload with STDIN from a text file giving wrong result for mean?
  • Download Code