Sunday, 15 July 2012

String partitioning (converting complex string to an array) in perl -



String partitioning (converting complex string to an array) in perl -

there big string s, contains item codes comma delimited.

e.g.:

$s="90320,328923,skjs32767,dsikudiu,829eue,ausiud0q897,ajiue98, 387493420da,93re,akdj93,sadi983,90439,jadkj84";

in application these strings passed function, returns cost of these items, i.e. output of function corresponding cost item code input.

however, due limitations, maximum length of $s should not exceed 16. if length of $s exceeds 16, exception thrown. thus, these strings should partitioned array, such that, length of each element of array less or equal 16.

e.g: after partitioning $s, array is:

$arr[0]='90320,328923',#note first 16 char 0320,328923,sk. however, sk neglected incomplete(being partial) item code. $arr[1]='skjs32767', $arr[2]='dsikudiu,829eue', $arr[3]='ausiud0q897', $arr[4]='ajiue98', $arr[5]='387493420da,93re'

for given $s, function should homecoming array, next constraints noted above.

my approach has been utilize substr function, , extract string 16 offset, updated position index. can done in improve way?

this simple using global /g regular look match.

this programme demonstrates. regex pattern looks many characters possible maximum of 16 must followed comma or end of string.

however, first thought same robearl's comment - why not set 1 field string each element of array? there need pack more 1 element because possible?

use strict; utilize warnings; utilize 5.010; $s = '90320,328923,skjs32767,dsikudiu,829eue,ausiud0q897,ajiue98,387493420da,93re,akdj93,sadi983,90439,jadkj84'; @partitions; while ( $s =~ /\g(.{0,16})(?:,|\z)/g ) { force @partitions, $1; } @partitions;

output

90320,328923 skjs32767 dsikudiu,829eue ausiud0q897 ajiue98 387493420da,93re akdj93,sadi983 90439,jadkj84

string perl

No comments:

Post a Comment