use Modern::Perl; sub extract { my ($data, $separator, @fields) = @_; return join $separator, (split(/$separator/, $data))[@fields]; } my $input = 'First#second#third#and this is field no. 4#FIVE5five5#all sixes 666#Seventh and last'; my $extraction = extract($input, '#', 1, 3, 4, 6); say $extraction;