Wikipedia:Reference desk/Archives/Computing/2021 March 17

= March 17 =

Perl character extraction
Is there a neater way in perl of grabbing the "nth" character from a string and then removing it from the string?

The following "works", but it doesn't feel very perl-ish to me. Is there a better way? (All characters in strin are different.) my $ch = substr( $strin, $n, 1 ) ;   # Grab character n (my $strout = $strin) =~ s/$ch// ;    # Remove ch from strout

-- SGBailey (talk) 08:35, 17 March 2021 (UTC)


 * I'm no expert, but I would use the substr function, with the replacement parameter. I think it is easier to understand than regexp. I have an idea it is faster too (not that this makes any difference unless you are processing large numbers of strings). --TrogWoolley (talk) 13:01, 17 March 2021 (UTC)


 * Thank you - that works nicely

my $strin = "abcdef" ; my $n = 3; my $ch = substr( ($strout = $strin), $n, 1, '' ) ;   # Grab character n print "$strin    $strout    $ch\n" ; =result abcdef   abcef    d Press any key to continue. . . =cut -- SGBailey (talk) 14:20, 17 March 2021 (UTC)


 * You can also use substr on the left side of an assignment statement to remove a character:

substr($str,$n,1) = "";
 * CodeTalker (talk) 18:05, 17 March 2021 (UTC)