1

I have some issues with a regular expression in perl. I'm trying to add a string at the beginning of a another string (in fact, insert a string at the beginning of the name of a file). What I want is check before inserting that string if the file already begins by it.

This is the code I have:

if ($ficheroSinExt !~ m/^$strCadena/){
    # if it doesn't exist at the beginning, I insert it...
    $ficheroSinExt = $strCadena . " " . $ficheroSinExt;
}
else{
    print "---->It already exists!!!\n";
}

I'm testing it with two filenames with only one containing [Perl] at the beginning ("[Perl] File1.pdf" and "File2.pdf"), and $strCadena contains [Perl]. I end up adding [Perl] for both files, so their new names are "[Perl] [Perl] File1.pdf" and "[Perl] File2.pdf".

I think the problem comes from the ^$strCadena of the match operator, but I don't arrive to work-around it. Could you please give me a hand?

Thanks in advance, Diego

1
  • $ficheroSinExt =~ s/^(?! \Q$strCadena\E )/$strCadena /x; Commented Nov 18, 2014 at 16:26

2 Answers 2

1

Quote the special characters:

if ($ficheroSinExt !~ m/^\Q$strCadena/){
#                  here __^
Sign up to request clarification or add additional context in comments.

Comments

1

You want to disable pattern metacharacters (see perlre)

if ($ficheroSinExt !~ m/^\Q$strCadena\E/){

1 Comment

Thanks for your response and for the reference!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.