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



Hi Monks,

I am getting a string into ARGV[0] from command prompt such as "C:\dirname\*" So that I can show the list of files in that path. Now to process on this string I want to remove '*' character from the end. I used 'chop' but it removes \n.

Can anyone please help how to do it ?

Thanks.

Devdatta
  • Comment on how to chop last character from a string

Replies are listed 'Best First'.
Re: how to chop last character from a string
by ikegami (Patriarch) on Jan 03, 2006 at 19:44 UTC

    Why does $ARGV[0] contains a newline? chop will remove the last character, no matter what it is. The following should be more reliable than chop:

    my $arg = $ARGV[0]; $arg =~ s/\*$//; # Remove trailing '*', if any.

    If there really is a newline, add chomp($arg) between those two lines.

    Of course, you probably you could forget about removing the '*' and use File::Glob or File::DosGlob to interpret the argument (if you're trying to list the files matching the spec).

      Why add a chomp, if you are already regexping just give it a
      $arg =~ s/\*\n?$//;
      if you actually want to get rid of trailing newlines.... maybe add a \r? for completeness' sake

                      - Ant
                      - Some of my best work - (1 2 3)

Re: how to chop last character from a string
by choedebeck (Beadle) on Jan 03, 2006 at 19:44 UTC
    well, if chop removed a \n then the last character of that string was \n. Why can't you just chop again? If that doesn't appeal to you you could do something like
    $ARGV[0] =~ s/\*.*$//;
    That should do it too.
      That will do a lot more than remove a trailing *, if there is ever anything else after the *...

                      - Ant
                      - Some of my best work - (1 2 3)

      Rather than chopping twice a safer way would be to chomp first then chop.

      But, I like the regex solutions better than chopping

      Mike

Re: how to chop last character from a string
by suaveant (Parson) on Jan 03, 2006 at 21:26 UTC
    Of course, if you wanted to be lazy you could do a chomp then a chop, since chomp only grabs whitespace you will take off a \n if it is there but not break if it isn't... it is very strange that you have a \n in the argument, though.

                    - Ant
                    - Some of my best work - (1 2 3)