Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: Replace $a with $b if $a ne $b

by Anonymous Monk
on May 06, 2005 at 19:06 UTC ( [id://454780]=note: print w/replies, xml ) Need Help??


in reply to Replace $a with $b if $a ne $b

I apologize, at the time of writing I thought it was clear. What is happening is I am looping through a list of files and I don't want to reprint the directory the files reside in for every single file. So I am trying to set $a to $b as $b changes and I am also setting $b to "" if it matches $a.
foreach $file (@filelist) { ($dir, $name) = split '/', $file; $dir =~ s/$currentdir//; printf("%s %s\n", $dir, $name); $currentdir !~ s/$dir/$dir/; }
so I will hopefully get output like
DIR1 FILE1 FILE2 FILE3 DIR2 FILE4

Replies are listed 'Best First'.
Re^2: Replace $a with $b if $a ne $b
by Roy Johnson (Monsignor) on May 06, 2005 at 19:27 UTC
    Once you've cleared $dir, it's useless to compare $currentdir to it. Maybe you want something like:
    my $printed_dir = ''; foreach $file (@filelist) { my ($dir, $name) = split '/', $file; printf("%s %s\n", ($dir eq $printed_dir ? '' : $dir), $name); $printed_dir = $dir; }

    Caution: Contents may have been coded under pressure.
Re^2: Replace $a with $b if $a ne $b
by graff (Chancellor) on May 08, 2005 at 04:12 UTC
    There are at least a few different (and sensible) ways to do what you want in that "foreach" loop. Personally, I'd opt for turning the list into a hash of arrays, so that it is structured in a way that is consistent with what the output should be:
    my %dirhash; for my $file ( @filelist ) { my ( $dir, name ) = split '/', $file; pushd @{$dirhash{$dir}}, $name; } for my $dir ( sort keys %dirhash ) { print "$dir\t", join( "\n\t", @{$dirhash{$dir}} ), "\n"; }
    Another way, more similar to your original idea, would be to keep track of what the last printed directory was, and only print the directory name when it changes from the previous:
    my $lastdir = ''; for my $file ( @filelist ) { my ( $dir, $name ) = split '/', $file; if ( $dir ne $lastdir ) { print "$dir"; $lastdir = $dir; } print "\t$name\n"; }
Re^2: Replace $a with $b if $a ne $b
by holli (Abbot) on May 08, 2005 at 06:55 UTC
    You shouldn't use a regex to split the filename from the path. Better take File::Basename for that.
    use File::Basename; my ($name,$path) = fileparse($fullname);


    holli, /regexed monk/

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (4)
As of 2024-04-25 07:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found