Does anyone know how to ignore the rest of a line in Perl? I am reading a file and printing out tokens to an output file. I want to ignore the rest of a line after a colon is found, which indicates a comment. That way it will not print to the output file. I tried a range from (; - \n) but it does not work. Thanks for any input.

My personal suggestion, would be to do a split or regex on it. I would do a split, but I'm a bit silly. The thing is, if a colon starts a comment, then there can be no colon's within the "good string". what I mean is, if the line has:

she said: how are ya :this is the comment

then "she said" would be the only thing that would not be a comment. But, This is how I would do it:

($goodinfo, $comment) = split(/:/, $_) # you can replace $_ with the variable you use
print FH "$goodinfo\n";

obviously, the above line will need modifications in order to suite what it is you are doing, but split line works by searching for a colon, if it finds one, it sticks the stuff on the left of the colon, into the first variable, and the stuff on the right in the second variable (those that are in parenthesis). You could have it return an array, also, and just do a pop on the array, but in that way, only the data after the very last colon in the string would be ignored. Let me know what you come up with.

I wouldn't normally double post, but I found the best way that I would do it, and converted it into a sub that you can use:

sub strip_comment
{
        # /* Get The Parameter Passed To The Function */
        $theline = shift;

        # /* Search For The First Occurance Of : */
        $where = index($theline, ":");

        # /* If We Find No Comment, Return The Entire Line Passed To us */
        if ($where eq -1) {
                return $theline;
        }

        # /* Get The Part Of The String Up To, And Including The Colon */
        $goodpart = substr($theline, 0, $where);

        # /* Remove The Colon */
        chop($goodpart);

        # /* Return Only The Portion Of The String Before The Colon */
        return $goodpart;
}

just stick that at the bottom of your perl file, and then call it like this:

$retval = &strip_comment($theline);

Assuming $theline was the entire line, comments and all, then $retval would contain only the non-comment part of the line. Let me know how it works for you.

This article has been dead for over six months. Start a new discussion instead.