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

Monks, I hope you can tell what I'm trying to do here even though there is a flaw in my code. It does not work. I'm trying to insert a first name if it is not already in a text field.
if ($text !=~ m/$firstname/ && $type eq "login") { $text = "<b>$firstname:</b> " . $text; }
I'm not sure what I'm doing wrong, but it inserts the first name in every text field that has the type login.

Replies are listed 'Best First'.
Re: Matching text in a string
by BrowserUk (Patriarch) on Apr 16, 2015 at 09:11 UTC

    This: !=~ should be this: !~.

    The condition is being seen as $text  !=  ~ m/$firstname/ && $type eq "login", which with warnings enabled would have produced:

    !=~ should be !~ at ... Use of uninitialized value $_ in pattern match (m//) at ... Argument $text isn't numeric in numeric ne (!=) at ...

    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority". I'm with torvalds on this
    In the absence of evidence, opinion is indistinguishable from prejudice. Agile (and TDD) debunked

      It might well be that !=~ should be this: =~. See Corion's question re the logic.

      UPDATE: Forget it, I did not read the OP's question carefully enough...

        I think the OPs logic is clear; he just mixed up his operator. (His implementation may also be flawed!)


        With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
        Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
        "Science is about questioning the status quo. Questioning authority". I'm with torvalds on this
        In the absence of evidence, opinion is indistinguishable from prejudice. Agile (and TDD) debunked
      Thanks! That's it.
Re: Matching text in a string
by Corion (Patriarch) on Apr 16, 2015 at 09:12 UTC

    You never show us where you actually output $text. Also, you don't show us the values of $firstname and the overall program logic.

    Also, consider what happens when my firstname is A - do you really want to skip adding my first name then?

    Update: Also see BrowserUks reply, which points out the more likely the cause of your immediate problem.

    Update 2: You really should consider using a template system instead of trying to munge HTML that has already been created afterwards. First create all the data you need and then create the HTML. Don't create HTML while running through your program.

Re: Matching text in a string
by Your Mother (Archbishop) on Apr 16, 2015 at 15:06 UTC