PerlLoveMe has asked for the wisdom of the Perl Monks concerning the following question:

How can i get a character in a string at any position with out use substr() function?

Replies are listed 'Best First'.
Re: Get char in string
by sauoq (Abbot) on Oct 24, 2003 at 05:46 UTC

    There are many ways...

    sub getchar_unpack { my ($string, $index) = @_; return unless $index >= 0 and $index < length($string); return chr( (unpack 'C*', $string)[$index] ); } sub getchar_split { my ($string, $index) = @_; return unless $index >= 0 and $index < length($string); return ( (split //, $string)[$index] ); } sub getchar_loop { my ($string, $index) = @_; return unless $index >= 0 and $index < length($string); $string = reverse $string; my $c; $c = chop $string until $index-- == 0; return $c; }

    But why?

    -sauoq
    "My two cents aren't worth a dime.";
    
Re: Get char in string
by Zaxo (Archbishop) on Oct 24, 2003 at 06:42 UTC

    I'd just get reckless and call substr, anyway.

    After Compline,
    Zaxo

Re: Get char in string
by nevyn (Monk) on Oct 24, 2003 at 05:29 UTC

    Assuming you mean get the X numbered character from the string, you could do...

    sub chr_at { my ($data, $skip) = @_; --$skip; $data =~ /^.{$skip}(.)/; $1; } for (1..4) { print chr_at("abcd", $_) . "\n"; }

    ...but I wouldn't be supprised if the substr() version is faster.

    -- James Antill
Re: Get char in string
by davido (Cardinal) on Oct 24, 2003 at 04:59 UTC
    Hmm... do you mean get an unknown character from a known position, or a known character from an unknown position? The answer will be different depending on those kinds of specifics.


    Dave


    "If I had my life to do over again, I'd be a plumber." -- Albert Einstein
Re: Get char in string
by jacques (Priest) on Oct 24, 2003 at 06:01 UTC
    My first thought was charAt(), but that's Java.

    Perl doesn't have those oh-so-convenient functions/classes found in PHP or Java. I guess because then everyone would want a function for everything under the sun, and we would get feature creep... On the other hand, people accuse us of trying to jam too much into Perl, while knocking us for not having more of these shortcuts which would (supposedly) reduce idiosyncracies and increase standardization and maintainability.

    Oh wait, there's CPAN. That's right.