how to chop last character from a string
Anonymous Monk
created: 2006-01-03 14:40:30


Hi Monks,

I am getting a string into ARGV0 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
Re: how to chop last character from a string
created: 2006-01-03 14:44:15

Why does $ARGV0 contains a newline? [doc://chop|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).

Re^2: how to chop last character from a string
created: 2006-01-03 16:31:20
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 [/index.pl?node_id=56739#Best|best] work - (1 2 3)

Re: how to chop last character from a string
created: 2006-01-03 14:44:56
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.
Re^2: how to chop last character from a string
created: 2006-01-03 16:28:07
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)

Re^2: how to chop last character from a string
created: 2006-01-04 10:26:37

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
created: 2006-01-03 16:26:20
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)

perlmonks.org content © perlmonks.org and Anonymous Monk, bioMan, choedebeck, ikegami, suaveant

prlmnks.org © 2006 edmund von der burg (eccles & toad)

v 0.03