Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

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:

Hi,

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.

Cheers,

Elfyn

Comment on dodgy sub
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.
    HTH

    broquaint

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 :)

      Elfyn

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (5)
As of 2014-08-30 08:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (291 votes), past polls