http://www.perlmonks.org?node_id=1184635


in reply to Re: following if condition fails to print its variable using perl?
in thread following if condition fails to print its variable using perl?

my $name_map = read_map( $mapfile ); my ($regex) = map {qr /\b(?:$_)\b/ } join '|', map {quotemeta} keys %$ +name_map; my $top_dir = $output_dir; rename_dirs( $top_dir, $name_map, $regex ); sub rename_dirs { my ( $top_dir, $name_map, $regex ) = @_; opendir (my $dh, $top_dir) or die "Can't open $top_dir: $!"; my $save_dir = getcwd(); chdir $top_dir; while (my $name = readdir $dh) { next if ($name eq '.') or ($name eq '..'); #print $name,"\n"; if ( ( -d $name ) && ( exists $name_map->{$name} ) ) { #print $name; my $new_name = $name_map->{$name}; #print $new_name; rename_file_or_dir( $name, $new_name ); $name = $new_name; #print $name; } elsif ( -f $name ) { if (( my $base_name = $name) =~ s/\.config$// ) { if ( $name_map->{$base_name} ) { my $new_name = $name_map->{$base_name} . '.config' +; # print $new_name; rename_file_or_dir( $name, $new_name ); change_file( $mapfile, $name_map, $regex ); } } } rename_dirs( $name, $name_map, $regex ) if -d $name; } chdir $save_dir; } sub change_file { my ( $fn, $map, $regex ) = @_; print $fn; open ( my $fh, '<', $fn ) or die "Could not open file '$fn': $!"; my $str = do { local $/; <$fh> }; close $fh; my $num_replacements = $str =~ s/($regex)/$map->{$1}/ge; if ( $num_replacements ) { write_new_file( $fn, \$str ); } } sub write_new_file { my ( $fn, $str ) = @_; open ( my $fh, '>', $fn ) or die "Could not open file '$fn': $!"; print $fh $$str; close $fh; } sub rename_file_or_dir { my ( $name, $new_name ) = @_; File::Copy::move( $name, $new_name ) or die "Could not rename '$name' as '$new_name': $!"; } sub read_map { my ( $fn ) = @_; my %name_map; open( my $fh, '<', $fn ) or die "Could not open file '$fn': $!"; while( my $line = <$fh> ) { chomp $line; my @fields = split /:/, $line; # print @fields; if ( @fields == 3 ) { $name_map{$fields[2]} = $fields[1]; } } close $fh; return \%name_map; }
i hope by above code you can understand the complete flow.am trying to match directories and files at same block that is rename_dirs.Here i am struck with print $new_name and above lines.Help me to get it.Thanks in advance