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

This is a really simple question, but I cann't seem to make the translation from sed -> perl? All I'm trying to do is convert:

s/oh/Ohio/g into Perl.

Reading a file containing state names in from the command line. (i.e. perl -w states.pl states.dat >states.db): Here's what I tried:

while (<>){ s/oh/Ohio/g; }
Thanks, David

Replies are listed 'Best First'.
Re: Win32: sed -Perl
by belg4mit (Prior) on Jan 23, 2002 at 07:03 UTC
    perl -pi~ -e 's/oh/Ohio/g'; Try reading perlre and perlrun (pay special attention to -i), they ought to give a thorough explanation of what goes on there. Suffice it to say -p makes perl act like a stream editor (sed). UPDATE: To clarify that doesn't make perl act like *the* sed though.

    --
    perl -pe "s/\b;([st])/'\1/mg"

Re: Win32: sed -Perl
by talexb (Chancellor) on Jan 23, 2002 at 08:04 UTC
    When you see
    while (<>) { # Do something here }
    in someone's code, that means a loop that is reading each line of the intput stream. (The command line equivalent, as has already been pointed out, is perl -n.) If all you want to do is echo that, then you'd add a print statement to output the current line (when used without arguments, the print statement conveniently uses $_, which holds the current element being examined .. in this case, it's the input line just read in).
    while (<>) { print; }
    This is pretty useless, as it just dumps out the input. To actually make a change (like your Ohio change) add an s operation.
    while (<>) { s/oh/Ohio/g; print; }
    Now, this may not work the way you expect it to. Alcohol, cohabitate, cohesion, microhmmeter and our fuzzy friend pooh will all match with 'oh'. But the rest (heh heh) is left as an exercise for the student.

    --t. alex

    "Of course, you realize that this means war." -- Bugs Bunny.

Re: Win32: sed -Perl
by trs80 (Priest) on Jan 23, 2002 at 07:22 UTC
    You could also do this:
    while (<>){ s/oh/Ohio/g; print; }
    Your example code wasn't producing any output so there was nothing to add to the states.db file.
Re: Win32: sed -Perl
by Anonymous Monk on Jan 23, 2002 at 08:08 UTC
    It really was simple, as I thought. Thanks for the pointers to the man pages. David