Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: File ext number

by ikegami (Patriarch)
on Mar 19, 2010 at 23:20 UTC ( [id://829723]=note: print w/replies, xml ) Need Help??


in reply to File ext number

Your match doesn't match when readdir returns ., so $1's value isn't changed by the match, and it was previously undefined.

use strict; use warnings; my %ext; opendir my $dh, './' or die $!; for (grep { -f } readdir $dh) { ++$ext{$1} if /\.([^.]+)$/; } print "$_ - $ext{$_}\n" for keys %ext;

Alternate:

use strict; use warnings; my %ext; opendir my $dh, './' or die $!; ++$ext{$1} for map { -f && /\.([^.]+)$/ ? $1 : () } readdir $dh; print "$_ - $ext{$_}\n" for keys %ext;

Replies are listed 'Best First'.
Re^2: File ext number
by toolic (Bishop) on Mar 19, 2010 at 23:38 UTC
    Your match doesn't match when readdir returns .
    Are you saying that the dot (.) directory somehow makes it past the grep {-f} filter in the OP's code? I freely admit I have no idea what that whole line does in the OP's code, but it would be surprising to me if . made it past the filter.

      Are you saying that the dot (.) directory somehow makes it past the grep {-f} filter in the OP's code?

      I guess I was without realizing it. Obviously, that's not true and my explanation is wrong. Take two:

      $ext{$1} += (m/([^.]+)$/);
      means something close to
      $ext{$1} = $ext{$1} + (m/([^.]+)$/);

      Well, actually more like the following, but it doesn't matter for this discussion:

      alias $temp = $ext{$1}; $temp = $temp + (m/([^.]+)$/);

      Either way, you are relying on Perl evaluating the RHS of the "+=" operator before its LHS, and that's not how Perl operates. In fact, Perl doesn't document how it operates in this circumstance, and that's the reason it's generally a no-no to change and use the same variable in the same expression.

      Even though my earlier explanation was wrong, the solutions I posted still avoid the problem.

      Update: Improved phrasing by inlining footnotes.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://829723]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (4)
As of 2024-03-28 17:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found