Jump to content

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

From Wikipedia, the free encyclopedia
Computing desk
< March 16 << Feb | March | Apr >> March 18 >
Welcome to the Wikipedia Computing Reference Desk Archives
The page you are currently viewing is a transcluded archive page. While you can leave answers for any questions shown below, please ask new questions on one of the current reference desk pages.


March 17[edit]

Perl character extraction[edit]

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)[reply]

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)[reply]
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)[reply]

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)[reply]