my $cur_smp = 0; my $len = length($input_data) / 2; foreach (unpack("s*",$input_data)) { # take the value and add to it the sample value # five samples ahead if($len < $cur_smp + 5) { # if we don't have enough samples left to look ahead, # just go with what we've got $output .= pack("s",$_); $cur_smp++; next; } my $five_ahead = unpack("s",substr($input_data,($cur_smp + 5) * 2,2)); $output .= pack("s",$_ + $five_ahead); $cur_smp++; next; }