Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: substitute 4 spaces instead of a tab

by anneli (Pilgrim)
on Nov 07, 2011 at 09:05 UTC ( #936441=note: print w/replies, xml ) Need Help??


in reply to substitute 4 spaces instead of a tab

Some comments.

  • Be sure to use strict; and use warnings;—they will catch bugs in your code so you don't have to.
  • Bare filehandles ("FH") are discouraged. Use open(my $fh, "<", $tu), three-argument open.
  • You've escaped the tab character so it actually means the literal string \t instead of a tab! Use $line =~ s/\t/    /g;, not \\t
  • You're not actually writing the results of your substitution out. You need to open another filehandle for writing, and write to that. Don't open the same file you're reading from, otherwise you may truncate it before you have a chance to read it.
  • You need to be careful; there may be tabs used not for indenting (as part of the actual code). You might want to use some anchoring (\A or ^) in your regular expression.
  • Your editor or other tools can probably do this already for you, and have already worked out the edge cases so you don't have to. Consider using those.

Anne

Replies are listed 'Best First'.
Re^2: substitute 4 spaces instead of a tab
by anneli (Pilgrim) on Nov 07, 2011 at 10:40 UTC

    With regards to not truncating anything accidentally, davido mentioned this excellent suggestion: move the original file out of the way first (e.g. if it's called shock_api.h, call it shock_api.h.bak or similar; there's a built-in called rename to do this), then read in from shock_api.h.bak and write out to shock_api.h.

    This solves the simultaneous read/write truncation issue, and creates a backup for you in case things go awry.

      In fact my suggestion isn't exactly original either. Take a look at perlrun under the -i flag. When you instruct Perl do to in-place edits from the command line like this, "perl -i.bak ....." you get essentially the same behavior.


      Dave

Re^2: substitute 4 spaces instead of a tab
by JavaFan (Canon) on Nov 07, 2011 at 16:27 UTC
    Be sure to use strict; and use warnings;—they will catch bugs in your code so you don't have to.
    Yeah, but it doesn't actually help catching the bug the OP is struggling with, does it?
    Bare filehandles ("FH") are discouraged. Use open(my $fh, "<", $tu), three-argument open.
    Bollocks. There's nothing wrong with the filehandle or the open the OP used.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (4)
As of 2022-05-23 11:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you prefer to work remotely?



    Results (81 votes). Check out past polls.

    Notices?