in reply to removing comments

That would work if you ran the program like so:

perl -i -pe 's/^\s*\'.*//' targetfilename

On the perlrun page you can see why this works (along with examples of how -p and -i expand).

You are running your substitution on the filename rather than on any of the contents of it.

-Paul

Replies are listed 'Best First'.
Re^2: removing comments
by dhudnall (Novice) on Jun 21, 2007 at 15:32 UTC
    that would work if I am running the command from the command line but I would like to be able to do it inside my program instead of having to run a command from the command line but I don't know how. Would I do something like:
    $TheFile = $ARGV[0]; open (INFILE, $TheFile) or die while(<INFILE>) { perform the removal of the comments here...or what?!? and if so what w +ould the syntax be. }
    I would just like to immediately remove all comments before going any further into my massive program.
      Do you want to have the entire file in memory? What do you plan to do with it, apart from removing comments? For any one line of the file, s/^'.*// will clear the comment text, leaving a blank line in its place.

      Caution: Contents may have been coded under pressure.
      Your question is a bit ambigious. Do you want to
      1. create a new file with no comments
      2. load the file into memory and strip the comments before further processing
      ?

      variant 1:
      open (my $in, "<", $ARGV[0]) or die "in: $@"; open (my $out, ">", "$ARGV[0].new") or die "out: $@"; while( my $line = <$in>) { print $out $line unless $line =~ /^#/; } close $in; close $out;
      variant 2:
      open (my $in, "<", $ARGV[0]) or die "in: $@"; my @lines = grep { not /^#/ } <$in>; #<> here in list context, therefo +re no explicit loop
      Note that you cannot erase a line from the middle of a file, you will always have to write a new one. But you already knew that, didn't you? ;-)


      holli, /regexed monk/

        Or, given the file name is in @ARGV anyway:

        $^I = '.bak'; /^#/ or print while <>;

        to in place edit and generate a backup file.


        DWIM is Perl's answer to Gödel

      You'd have to open an input and an output file — generally they're not the same one, unless you're very clever about it.

      There is actually an example on the page I linked but it may have been unobvious to locate.

      open my $input, "<", $ARGV[0] or die "couldn't open $ARGV[0]: $!"; open my $output, ">", "output.txt" or die "coudln't open output: $!"; while(<$input>) { if( m/something/ ) { # do stuff } s/stuff//g; # etc. print {$output} $_; } close $output; close $input;

      -Paul