in reply to Add a fixed number of unique elements to hash

Define "very large number".

Anyways, here's one way I'd do it (who needs recursion?).

#!/usr/bin/perl use strict; # https://perlmonks.org/?node_id=11150757 use warnings; use List::AllUtils qw( sample none ); my $target = "/home/zsolti/Temp"; $target = '../mnt/home/old'; # FIXME for testing on my system my @exclude = ( #'2023_02_21_Szentendre_Pilis_EK_oldal' 'webftp' ,'x' ); my (@audioFiles, %playList); my $numOfRandFiles = 10; my @queue = $target; while( defined( my $path = pop @queue ) ) { if( -f $path and $path =~ /\.mp3$/i ) { push @audioFiles, $path; } elsif( -d $path and none { $path =~ m{/\Q$_\E\z} } @exclude ) # prun +e { push @queue, <$path/*>; } } @playList{ sample $numOfRandFiles, @audioFiles } = 1 .. $numOfRandFile +s; use Data::Dump 'dd'; dd \%playList;

Replies are listed 'Best First'.
Re^2: Add a fixed number of unique elements to hash
by tybalt89 (Monsignor) on Mar 06, 2023 at 01:51 UTC

    Hmmm, 5.004 - well at least it's not perl 4

    #!/usr/bin/perl use strict; # https://perlmonks.org/?node_id=11150757 use warnings; my $target = "/home/zsolti/Temp"; $target = '../mnt/home/old'; # FIXME for testing on my system my @exclude = ( #'2023_02_21_Szentendre_Pilis_EK_oldal' 'webftp' ,'x' ); my (@audioFiles, %playList); my $numOfRandFiles = 10; my @queue = $target; while( defined( my $path = pop @queue ) ) { if( -f $path and $path =~ /\.mp3$/i ) { push @audioFiles, $path; } elsif( -d $path and not grep $path =~ /\/\Q$_\E\z/, @exclude ) { push @queue, <$path/*>; } } $playList{ splice @audioFiles, rand @audioFiles, 1 } ||= $_ for 1 .. $numOfRandFiles; printf "%3d %s\n", $playList{$_}, $_ for sort keys %playList;

    Though since I don't actually have a perl 5.004 to test on, I do wonder if it works...

      "Though since I don't actually have a perl 5.004 to test on, I do wonder if it works..."

      The only thing that I can see which won't work is 'use warnings;':

      $ corelist warnings Data for 2022-05-27 warnings was first released with perl v5.6.0

      Replace with '$^W = 1;'.

      — Ken

      Simplifying a little

      #!/usr/bin/perl use strict; # https://perlmonks.org/?node_id=11150757 #use warnings; # uncomment for newer perls my $target = "/home/zsolti/Temp"; $target = '../mnt/home/old'; # FIXME for testing on my system my @exclude = ( #'2023_02_21_Szentendre_Pilis_EK_oldal' 'webftp' ,'x' ); my (@audioFiles, %playList); my $numOfRandFiles = 10; my @stack = $target; while( my $path = pop @stack ) { grep $path =~ /\/\Q$_\E\z/, @exclude and next; push @audioFiles, grep -f, <$path/*.mp3>; push @stack, grep -d, <$path/*>; } $playList{ splice @audioFiles, rand @audioFiles, 1 or last } = $_ for 1 .. $numOfRandFiles; printf "%3d %s\n", $playList{$_}, $_ for sort keys %playList;