pcadv has asked for the wisdom of the Perl Monks concerning the following question:

Newbie here
I'm having a problem with the returned list of files of my directory
how do I remove the last comma from my list
I know it involves chomp but I can't seem to get it right
---code---
use Cwd; my $dir = getcwd; opendir (DIR, $dir) or die $!; my @dir = readdir DIR; foreach my $item (@dir) { print "$item," if -r $item and -w $item and -x $item and $item =~ /^[a +-zA-Z]/ ; # Readable and not writable }
---end code---
any help is greatly appreciated
thanks
pcadv

20040208 Edit by ysth: code tags

Replies are listed 'Best First'.
Re: chomp a List
by blokhead (Monsignor) on Feb 07, 2005 at 22:01 UTC
    You cannot use chomp to erase characters you have already printed. For the logic of separating items by commas, Perl has the convenient join function. All you need to do is get the items you want to print into a list to pass to join. grep is a good way to do this:
    my @dir = readdir DIR; my @to_print = grep { -r $_ && -w $_ && -x $_ && /^[a-zA-Z]/ } @dir; print join "," => @to_print;

    blokhead

      print join "," => @to_print;
      I never saw this ! Does this means that one can use => instead of a coma everywhere ?
      Is there a precedence difference ?
      I'm used to do :
      print join(",", @to_print)
      which is obviously less idiomatic .

        => is almost the same as ,

        The difference is that => forces the value to the left of it to be interpreted as a quoted string

        This is why
        #!/usr/bin/perl -w my %a=( foo => "bar", fi , "fo");

        Will get you a warning for the unquoted fi, but not the unquoted foo. However, normal operator precedence still applies, so

        print join , => @to_print;
        won't work, whereas
        print join or => @to_print;
        will.
      Thank you for the help its almost to simple.
Re: chomp a List
by cog (Parson) on Feb 07, 2005 at 23:20 UTC
    Not that I recommend it, but you could print "\b" in the end.

    Still, blokhead's suggestion is better :-) I just wanted to point that there is more than one way to do it :-)

Re: chomp a List
by sh1tn (Priest) on Feb 08, 2005 at 00:06 UTC
    Not so elegant way:
    ... my $coutnter; for( @dir ){ print $_; $counter++; print ',' unless $counter == @dir; } ...