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

hi i'm not too familiar with regular expressions.. let's say i have
my $productcode = "FCLA"; #then $productcode =~ /FCL/ print $producecode #should return "FCL" only
what im trying to do is to get portion of the string out, according to what i specify. Is this possible? Cause there's like FCLA, FCLB, FCLCD, FCLXX, but im checking whether it belongs to FCL

Replies are listed 'Best First'.
Re: get a text out from a string
by moritz (Cardinal) on Feb 27, 2008 at 09:04 UTC
    You can do something like that:
    my $productcode = "FCLA"; if ($productcode =~ m/(FCL)/){ print "$1\n"; } else { print "No FCL in product code!\n"; }

    Or simply: $productcode = 'FCL' if $productcode =~ m/FCL/;

Re: get a text out from a string
by adrive (Scribe) on Feb 27, 2008 at 09:05 UTC
    so instead of :
    my $productcode = "FCLA"; if($productcode =~ /^FCL/){ $productcode = "FCL"; }
    is there a one liner that actually returns what i specify directly without having to write a conditional statement?
      What's wrong with a conditional statement? And what should happen to $productcode if it doesn'T start witch FCL?

      You can do something like this:

      $productcode = $productcode =~ m/^FCL/ ? : 'FCL' : "No, sorry";
      But that only hides the conditional in the ternary operator. And you can use parenthesis in the regex and access the matched value with $1, but you still need a conditional somewhere to check its value.
Re: get a text out from a string
by grizzley (Chaplain) on Feb 27, 2008 at 09:37 UTC

    Use substitute

    my $productcode = "FCLA"; $productcode =~ s/.*FCL.*/FCL/; print $producecode

      The only problem would be if what adrive wanted was to print out the original string (e.g., FCLA, FCLXXX, etc.) if it contains the user-specified substring (e.g., FCL).

      The solution with substitution would destroy the original string so that what would be printed would just be the sought-after substring.

      Of course maybe that what was wanted...I couldn't tell from the original qustion.

      ack Albuquerque, NM
      thanks guys :) that'll do