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

Hi

I'm trying to make a simple perl code that reads a code file and removes all comments (javascript style), like //... or /*... */ and /*....new line (number of time unknown)

Can someone give me an hand? Removing patterns like // or /*...*/ can be done, I think, with /\/+\*?\.*/gi but there are weird things on a random code. For instance, line breaks or the lines beginning with spaces or tabs. So I could do /([\ |\t]*)\/+\*?\.*/gi perhaps

Best regards

Replies are listed 'Best First'.
Re: Comments regex
by haukex (Archbishop) on Feb 25, 2020 at 09:52 UTC

    Use $RE{comment}{JavaScript} from Regexp::Common::comment:

    use warnings; use strict; use Regexp::Common qw/comment/; my $sample = <<'END_SAMPLE'; Hello // World a /* test */ b xyz /* asdf qwertz /* uiop */ ijk END_SAMPLE $sample =~ s/$RE{comment}{JavaScript}//g; print $sample; __END__ Hello a b xyz ijk

      Hi

      Great solution. I did not knew about that module - it's just incredible. Thank you so much. Best regards

Re: Comments regex
by cavac (Prior) on Feb 26, 2020 at 12:15 UTC

    If you want to minimize javascript (remove all comments and unneeded whitespace), there is a great module for that: JavaScript::Minifier

    perl -e 'use Crypt::Digest::SHA256 qw[sha256_hex]; print substr(sha256_hex("the Answer To Life, The Universe And Everything"), 6, 2), "\n";'