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

Thank you all for your assistance so far. I've been working with this and have a temporary solution.

To clarify my script takes in a different value every time ie.
$string = "mystring654321";

I should have been more clear that the input will always have six numeric characters at the end. I need to find what the first characters value is. In this case it will be a "6" but could change the next time.

My script then takes that value in and processes it further.
  • Comment on Re: How do I cut single characters out of a string

Replies are listed 'Best First'.
Re^2: How do I cut single characters out of a string
by GrandFather (Saint) on Jan 16, 2012 at 02:46 UTC

    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
      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; }