in reply to String Manupulation

I'm pretty new to perl too, so I don't understand everything about this command line example, but it seems like an easy way to solve your replacement task.
perl -pi.bak 's/ /-/' file.out

-ted-

Replies are listed 'Best First'.
Re: Re: String Manupulation
by Louis_Wu (Chaplain) on Sep 04, 2003 at 06:41 UTC
    I like the s/ /-/, but some of the surrounding syntax needs work. I'll present my version(s) first, then explain things.
    perl -pe 's/ /-/;' file.in > file.out or perl -pi.bak -e 's/ /-/;' file.out
    • All one-liners need the -e flag - that's what tells Perl that you are including the program on the command line. The -e needs to be right next to the code, with a space being optional. See perlrun if my silly explanation isn't sufficient.
    • I included the semi-colon as a good habit. Some one-liners can have more than one command in them, and the semi-colon can only be omitted from the last command. So I always include it.
    • In my first version I replaced the -i.bak with shell redirection. I just don't like in-place editing, no matter how backups are done. (If you erase the data in your file while inplace editing, and you just re-execute the oneliner, you are "editing" an empty file and overwriting your file.bak with emptiness. Result: you clobber all of your data, I hope your backups are quite recent.)

    I think that's it. You might want to check out -l for making all the line endings work nicely. This came up on the SPUG mailing list recently (SPUG: Docs on "-l" wrong?), where I described -l as "Automagically takes care of line endings, so you don't have to think about chomp or \n - high DWIMage factor." That's how it was first explained to me, and it covers the basics.

    We had one-liners come up on the SPUG mailing list in April (SPUG:Best One-Liners and Scripts for UNIX) and the discussion was quite instructive - that's where I started learning about the flags.

    Oh, yeah. One more flag which you need to know: -c will check your code to see if it compiles. Not strictly one-linerish, but it is technically a command line flag. :)


    Perl programming and scheduling in the corporate world, as explained by dragonchild:
    "Uhh ... that'll take me three weeks, broken down as follows: 1 day for coding, the rest for meetings to explain why I only need 1 day for coding."