# I just put it in $_ for example's sake. $_ = 'NCC045-071-109-SCC021-087-091-011545-'; @foo = split '-', $_; until($exp = pop @foo) {}; my $code; for(@foo) { if(s/^([A-Z]+)//) { #if there are letters at the front $code = $1; } push @{$data{$code}}, $_; # or do print $string_with_code = "$code$_\n"; }