Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"

dodgy sub

by emcb (Beadle)
on Feb 27, 2002 at 13:30 UTC ( #147893=perlquestion: print w/ replies, xml ) Need Help??
emcb has asked for the wisdom of the Perl Monks concerning the following question:


I have written a sub called str_replace. This sub is supposed to work the same as the php function str_replace. Heres the code:

sub str_replace
  my( $find,$replace,$what ) = @_;
  $what =~ s/$find/$replace/i;
  return $what;

I then use this function to find x and replace it with y in z like so:

$string = str_replace("Hi", "Hello", "Hello My Name Is Elfyn");

This function only returns 'Hi' instead of 'Hi My name Is Elfyn'. Any help on why fellow monks.



Comment on dodgy sub
Replies are listed 'Best First'.
Re: dodgy sub
by broquaint (Abbot) on Feb 27, 2002 at 13:42 UTC
    Try switching your parameters
    print str_replace("Hello", "Hi", "Hello My Name Is Elfyn\n");
    Also, since your implmentation of PHP's str_replace doesn't take 'mixed' value types (i.e strings, arrays, references etc), it's only a partial implmentation.


Re: dodgy sub
by strat (Canon) on Feb 27, 2002 at 13:43 UTC
    maybe you could try swapping hello and hi?
    $string = str_replace("Hello", "Hi", "Hello My Name Is Elfyn");
    Besides, if there are strange chars in $find ( \, +, *, (, [ or the like), better write:
    $what =~ s/\Q$find/$replace/;
    Otherwise, you may get nasty errors

    Best regards,
    perl -le "s==*F=e=>y~\*martinF~stronat~=>s~[^\w]~~g=>chop,print"

Re: dodgy sub
by dragonchild (Archbishop) on Feb 27, 2002 at 14:55 UTC
    Just so you're aware, you can do something like
    $string = str_replace(qr/(?:Hello)|(?:Hi)/, "Good-bye", "Hello My Name + is Elfyn");
    qr creates something that allows you to embed regex operators within a string to be used in a regex. :-)

    We are the carpenters and bricklayers of the Information Age.

    Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

      Thanks oh worthy monks.

      Im still learning regexps, and i thought my code was wrong. Oh it is :)


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://147893]
Approved by root
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (3)
As of 2015-10-04 20:26 GMT
Find Nodes?
    Voting Booth?

    Does Humor Belong in Programming?

    Results (104 votes), past polls