Perl parses the regex JavaScript file to catch quotes only at the beginning and end of the returned string

I'm just starting to learn Perl. I need to parse a JavaScript file. I came up with the following routine:

sub __settings {
    my ($_s) = @_;
    my $f = $config_directory . "/authentic-theme/settings.js";
    if ( -r $f ) {
        for (
            split(
                '\n',
                $s = do {
                    local $/ = undef;
                    open my $fh, "<", $f;
                    <$fh>;
                    }
            )
            )
        {
            if ( index( $_, '//' ) == -1
                && ( my @m = $_ =~ /(?:$_s\s*=\s*(.*))/g ) )
            {
                my $m = join( '\n', @m );
                $m =~ s/[\'\;]//g;
                return $m;
            }
        }
    }
}

I have the following regex that removes 'and ;from a string:

s/[\'\;]//g;

This works well, but if the string contains the mentioned characters ( 'and ;), then they are also deleted. This is undesirable and that I am stuck as it becomes a little more difficult for me and I'm not sure how to change the regular expression correctly:

  • Delete only the first 'in a row
  • Delete only the last 'in a row
  • Delete ont last ;in line if exists

Any help please?

+4
4

'

'

^[^']*\K'|'(?=[^']*$)

. .

https://regex101.com/r/oF9hR9/8

ont last; ,

;(?=[^;]*$)

. .

https://regex101.com/r/oF9hR9/9

^[^']*\K'|'(?=[^']*$)|;(?=[^;]*$)

.

+2

:

^'|';?$|;$

'' ( )

. DEMO

+3

:

#!/usr/bin/perl
$str = "'string; 'inside' another;"; 
$str =~ s/^'|'?;?$//g;
print $str;

IDEONE

The main idea is to use anchors: the ^beginning of the line, the $end of the line and ;?corresponds to the value ";" the character at the end, only if it is present (the ?quantifier makes the template preceding it optional).
EDIT : It is also ;deleted, even if the previous ones '.

+2
source

I suggest that your original code look more like this. This is a much more idiomatic Perl, and I find it easier to follow.

sub __settings {
    my ($_s) = @_;
    my $file = "$config_directory/authentic-theme/settings.js";
    return unless -r $file;

    open my $fh, '<', $file or die qq{Unable to open "$file" for input: $!};
    my @file = <$fh>;
    chomp @file;

    for ( @file ) {
        next if m{//};
        if ( my @matches = $_ =~ /(?:$_s\s*=\s*(.*))/g ) {
            my $matches = join "\n", @matches;
            $matches =~ tr/';//d;
            return $matches;
        }
    }
}
+1
source

All Articles