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

Thank you for your assistance with my previvous script but now I have a new problem. The create the files and prints to the them, but I want the format to be edit1.dat containing "$Blue Car Green" edit2.dat "Blue $Car Green" etc.., and the format I am getting is edit1.dat "$Blue Car Green" edit2.dat "$Blue $Car Green" etc... I thought it has something to do with the foreach loop, and after an hour of messing around with it I have gotten nowhere. Appreciate any help.

#!usr/bin/perl use File::Copy; print "What file would you like to edit? \n"; chomp($editfile = <>); copy($editfile, "edit.dat") || die "Cannot copy file: $!"; open(INFO,"edit.dat") || die "Can't open edit.dat: $!"; $header = <INFO>; undef $/; $sequence = <INFO>; my @twodarray = split(' ',$sequence); $list[0] = \@twodarray; $x=1; for ($j=0; $j<=$#{$list[0]}; $j++) { for ($k=0; $k<=$#list; $k++) { copy("edit.dat","edit$x.dat"); open(OTHER, ">edit$x.dat"); seek OTHER, 0 ,0; $position = $list[$k][$j]; $commentout = "\$"; $commentout = $commentout .= $position; #foreach $car(@twodarray){ $car =~ s/$position/$commentout/; print $car; print OTHER $car; } $x++; } print "\n"; } close INFO;

Replies are listed 'Best First'.
Re: Script printing undesired format
by johngg (Canon) on Jun 21, 2007 at 15:46 UTC
    A few points spring to mind. Firstly, it is strongly recommended that you put use strict; and use warnings; at the top of your scripts. This will force you to declare your variables, which helps avoid typos, and gives sanity warnings regarding dubious code.

    When slurping files it is worth localising the change to $/ within a small scope to avoid unwanted side effects elsewhere in the script

    my $header = <INFO>; my $sequence; { local $/; $sequence = <INFO>; }

    Once out of the code block, the previous value of $/ will be restored.

    I don't think the code as you have posted it will even compile as it looks as if you have mismatched braces now that the foreach is commented out.

    This line

    $commentout = $commentout .= $position;

    looks a bit wonky. Do either

    $commentout = $commentout . $position;

    or

    $commentout .= $position;

    Better still, just use one line

    my $commentout = '$' . $position;

    Double quotes interpolate variables, single quotes don't.

    As GrandFather points out, including samples of the input files and the expected output will help us to help you.

    Cheers,

    JohnGG

Re: Script printing undesired format
by GrandFather (Saint) on Jun 21, 2007 at 14:46 UTC