Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

test file with trailing whitespace

Status
Not open for further replies.

nix45

MIS
Nov 21, 2002
478
US
I'm trying to help a friend write a simple Perl script that will test whether or not a file exists or not, and if it does, write the name of the file in a file called exists.txt. The files that don't exist go in nonexist.txt. The script reads the names of the files from a file that looks like this...

"/etc/samba/smb.conf"
"/etc/nonexistent file"
"/usr/doesnt_exist"
"/var/log/messages"

Now, my script works perfect, except the problem is that some of his files have trailing whitespace at the end of the filename.

Code:
#!/usr/bin/perl -w

$a = '/root/testing/a.txt';
open(FILE, $a) or die "Can't open file: $!\n";
@lines = <FILE>;
close FILE;

$exists = '/root/testing/exists.txt';
open(EXISTS, ">$exists") or die "Couldn't open exists.txt for writing: $!\n";

$nonexist = '/root/testing/nonexist.txt';
open(NONEXIST, ">$nonexist") or die "Couldn't open nonexists.txt for writing: $!\n";

foreach (@lines) {
 $_ =~ s/"//g;
 chomp;
 if (-e $_) {
   print "$_ exists\n";
   print EXISTS "$_\n";
 } else {
   print "$_ doesn't exist\n";
   print NONEXIST "$_\n";
 }
}


How do you test if a file exists when it has trailing whitespace at the end?


Thanks,
Chris
 
This will clean the leading and trailing spaces off of a line of text.

Code:
my $string = '   Some String    ';
print "\|$string\|\n";
print "\|" . &trim($string) . "\|\n";

sub trim ($) {
	$_ = shift @_;
	chomp;
	s/^\s+//;
	s/\s+$//;
	return $_;
}
 
Code:
if (-e (trim($_)) {
...


sub trim {
    my @out= @_;
    for (@out) {
        s/^\s+//;
        s/\s+$//;
    }
    return wantarray ? @out : $out[0];
}


HTH
--Paul
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top