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

I have written a script using sed to edit. Unfortunately the sed version is old and i have to edit file to another one, then copy over it. So i thought id give perl ago. I played around with pie but cannot work out how to pass variables to it and use line numbers. A basic version of my Script:
#!/usr/bin/ksh test1() { eval sed -e $1 testfile > testfile2 } test1 "'1s/.*/test /'" #test1 "'1s/.*/ '$(tput smso)'broken'$(tput rmso)' /'"
So i pass a string to another function, which is read by SED. I have to use line numbers due to duplicate text entries in the text file im editing. In the sed line, im saying edit the first line.Substitue anything in that line with the word test. The second test (commented out) does a reverse video to highlight that text. Can anyone give me pointers as to how i can write the above in perl.

Replies are listed 'Best First'.
Re: Convert from Sed to Perl
by runrig (Abbot) on Apr 08, 2008 at 20:09 UTC
Re: Convert from Sed to Perl
by oko1 (Deacon) on Apr 08, 2008 at 22:16 UTC

    Your subject is a bit misleading; you're not converting from 'sed' to Perl - you're converting from a KSH script (which happens to use 'sed') to Perl. As much as I like Perl, and use it for almost every task, for a short script that mostly uses file operations, I'd stick with the standard Unix utils - although I'd do it somewhat differently.

    For one thing, since you're only writing your specified string into 'testfile2' - i.e., 'testfile' isn't actually being used in any way - then why not do exactly that? This example copies the action of your script:

    #!/usr/bin/ksh echo 'test ' > testfile2 # echo $(/usr/bin/tput smso)broken$(/usr/bin/tput rmso) > testfile2

    However, since this is a Perl forum:

    #!/usr/bin/perl -w use strict; open F1, "testfile" or die "testfile: $!\n"; open F2, ">testfile2" or die "testfile2: $!\n"; while (<F1>){ s/.*/test /; # s/.*/`tput smso`.'broken'.`tput rmso`/e; print F2; last; } close F1; close F2;
    
    -- 
    Human history becomes more and more a race between education and catastrophe. -- HG Wells