in reply to Building ARRAY with grep expression NOT working

Here is your code modified in a few ways:

The rest of your variable names have been left the same. If I were writing this myself I would lowercase them all but that's purely a stylistic thing.

#!/usr/bin/env perl use strict; use warnings; my %ujs; my $file = 'access_log.txt'; open my $FH, '<', $file or die "File $file not opened: $!"; while (my $String = <$FH>) { next unless $String =~ /([^\/]*\.js)/; $ujs{$1} = 1; } close $FH; print "$_\n" for sort keys %ujs;

Replies are listed 'Best First'.
Re^2: Building ARRAY with grep expression NOT working
by jwkrahn (Abbot) on Apr 01, 2020 at 01:49 UTC
    next unless $String =~ /([^\/]*\.js)/;

    You may also want to use an anchor so that ".js" only matches at the end of the string instead of anywhere in the string:

    next unless $String =~ /([^\/]*\.js)$/;
Re^2: Building ARRAY with grep expression NOT working
by Tux (Canon) on Apr 01, 2020 at 06:08 UTC

    • I've used postfix versions of unless and for to reduce the number of indented blocks.

    Which makes it harder for some (me) to read the code.

    The reason I answer is not because of that, but because of the wrong reason you state with it. It is easy to not have indentation and stil not use postfix unless and if as you already showed on line 7. I would prefer

    #!/usr/bin/env perl use strict; use warnings; my %ujs; my $file = "access_log.txt"; open my $fh, "<", $file or die "File $file not opened: $!\n"; while (<$fh>) { m/([^\/]*\.js)$/ and $ujs{$1}++; } close $fh; print "$_\n" for sort keys %ujs;

    Enjoy, Have FUN! H.Merijn
      open ... or ...

      is Perl idiom and completely acceptable.

      ... and ...;

      in place of

      ... if ...;

      is a sneaky use of a logical operator and short circuit evaluation that is more appropriate to golf than production code.

      I realise that eyes adapt over time, but explaining to a neophyte how and provides conditional code needs a lot more prose than explaining as postfix if.

      Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond
      A reply falls below the community's threshold of quality. You may see it by logging in.
Re^2: Building ARRAY with grep expression NOT working
by denting24by7 (Initiate) on Apr 02, 2020 at 04:58 UTC
    Thanks hippo. I really appreciate it. The log file is just an apache weblog. I was hopping to find all extensions of files requested. Any suggestions on a good starting point as in books? I have along way to go and I need to start parsing large logs and patch assessment logs, heavily. Thanks in advance to everyone for their help and for any more insight on learning material to start with.
A reply falls below the community's threshold of quality. You may see it by logging in.