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

i am having a file which contains different strings, which in turn are name of folders.
for example test.file has
test0002
intel/drivers/
here there can be spaces , tabs after folder names ( like we can place space after test0002 or it may happen when you edit file in notepad and use same in unix test0002 becomes test0002^M).
i used chop and chomp to do it. what i did was i read all contents in array then i did chop (or chomp) for each element of array but nothing works. i m unable to remove estra spaces, tabs.
how cn tis be done to get desired result

Replies are listed 'Best First'.
Re: how to use chop / chomp effectively
by duff (Parson) on Mar 24, 2006 at 01:58 UTC

    Don't use chop/chomp, but rather the substitution operator:

    my @lines = <$filehandle>; # read all lines s/\s+$// for @lines; # remove any whitespace at the end of eac +h line.
    In a regular expression, \s means "whitespace" which consists of spaces, tabs, carriage returns, line feeds, etc. The substitution says "substitute all whitespace at the end of the string with nothing", effectively removing it.

    chop just removes the last character, whatever it happens to be and chomp just removes the trailing input record separator character sequence (typically just \n)

Re: how to use chop / chomp effectively
by davidrw (Prior) on Mar 24, 2006 at 02:01 UTC
    Will it fit your needs to just strip all the whitespace from the end of the string?
    open FILE, '<', 'test.file' or die; while(<FILE>){ s/\s+$//; print "line=[$_]\n"; } close FILE;
    Note that you don't want to use chomp because you're looking to remove more than just $/ ... and you don't want to use chop because you don't want to accidentally remove a piece of the folder name..

      You've committed the cardinal sin of not checking the return value of your call to open :-)

Re: how to use chop / chomp effectively
by ptum (Priest) on Mar 24, 2006 at 02:16 UTC

    You will tend to get better responses if you post small, relevant portions of your code and are explicit about exactly what happens when 'nothing works'. Looks like you were lucky this time ... duff and davidrw have provided a good start to what you need. :)

    You might also consider reading How do I post a question effectively?.

    I think you're on the right track if you consider what characters can occur in a legal filename and build a regular expression that will filter out characters that fall outside that set. Write some code and post it here if you still need more help. :)


    No good deed goes unpunished. -- (attributed to) Oscar Wilde
Re: how to use chop / chomp effectively
by graff (Chancellor) on Mar 24, 2006 at 02:13 UTC
    Just in case there might be final space characters in the list, and in case it might be important to preserve those, you could do:
    s/[\r\n]+$//;