Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: sed in perl

by etcshadow (Priest)
on Aug 18, 2004 at 23:04 UTC ( #384145=note: print w/replies, xml ) Need Help??


in reply to sed in perl

So, as others mention, what you should be doing is simply:
$haha =~ s/tyre/tire/g;
(that's it... simple, no backticks, no need for invoking a subshell and sed, since sed is kind of just a very very limitted subset of perls functionality).

However, I'll also give the direct answer to your question: Perl and shell have a great deal in common, for example the $ sigil on variables, the interpolation of variables inside of double quotes ("...") and backticks (`...`), and the (shell) execution of a string in backticks. The important differences (for this example) are that

  • in perl, you need to use the $ sigil on your variables, even when they are on the left-hand side of an assignment (unlinke in shell)
  • shell will automatically handle whitespace* from the results of something executed by backticks (which perl will not do... perl will just give you the output of the subshell exactly, so, in this case, including the trailing newline from the echo | sed)
So in order to get the specific behavior you want doing this shell programming in perl, you'd have to do:
$haha=`echo -n $haha | sed "/tyre/tire/g"`;
There are only two actual differences (corresponding to the two bullets above):
  • changed haha=... to $haha=...
  • adding a -n option to echo. This makes echo not include a trailing newline. If echo had included that newline, then sed, too, would have passed that trailing newline, and perl would have not trimmed it off, so you've had ended up (inadvertantly) adding a newline to the end of $haha.

NOTE Regarding the shell and it's "handling" of whitespace: in general, the shell is actually going to be doing a lot more than just trimming the trailing newline... what the shell does is basically split all the output on any whitespace (including spaces, tabs, newlines), ignore any leading or trailing whitespace. It will use these "words" as a list, if the backtick is used in a list context, and rejoin the split-apart "words" with single spaces if it is using the results of the backtick as a string.

------------ :Wq Not an editor command: Wq

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (5)
As of 2019-10-19 16:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?