in reply to Re: How do I cut single characters out of a string
in thread How do I cut single characters out of a string

in which case a simple regular expression match is probably what you want:

if ($string =~ s/(\d)//) { my $digit = $1; ... } else { print "No digit in '$string'\n"; }

which finds and removed the first digit from $string. Putting the substitution inside an if allows you to deal with not finding a digit.

True laziness is hard work

Replies are listed 'Best First'.
Re^3: How do I cut single characters out of a string
by akechnie (Initiate) on Jan 16, 2012 at 06:12 UTC
    Ok I see what you did there
    Now say I want the ability to grab any character out of the hole string given the position of it.

    Such as mystring123456 so when I find the length of it with length(), so 14 characters. Is there a way I can tell it I want the 6th and 7th characters. Or then just grab the 9th character.


    #not actual code more just a logical walk through
    if(the string has 20 characters){
         Get the 9th character;
         Get the characters 6-8;
    }elsif(the string has 14 characters){
         Get the 6th character from the end;
         Get the last 4 characters from the end;
    }

    Sorry if this looks ugly but sometimes it helps me think through things like this.

      Read some of the earlier replies you received. The short version is: use substr.

      True laziness is hard work

      TIMTOWTDI but:

      use Modern::Perl; use Data::Dumper; my $dispatch = { 20 => sub { ( substr($_, 8, 1), substr($_, 5, 3) ) }, 14 => sub { ( substr($_, -6, 1), substr($_, -4, 4) ) }, }; my $string = 'mystring123456'; if (my $code = $dispatch->{ length $string }) { local $_ = $string; my @get = $code->(); print Dumper \@get; }