in reply to Re: removing comments
in thread removing comments

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.

Replies are listed 'Best First'.
Re^3: removing comments
by Roy Johnson (Monsignor) on Jun 21, 2007 at 16:27 UTC
    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.
Re^3: removing comments
by holli (Abbot) on Jun 21, 2007 at 16:35 UTC
    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
Re^3: removing comments
by jettero (Monsignor) on Jun 21, 2007 at 16:43 UTC

    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