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 SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

FIle Handling 3

Status
Not open for further replies.

M626

Programmer
Mar 13, 2002
299
0
0
Hi,

I am looking to do the following in perl. I know how to do it in vb but need it in perl.

I need a script to open a text file with test that contain file names, one per line. Once it opens the file, i need to remove the carage return and separate the file names by a space. Also, i need to have the script look at a directory and output the file names to a file is the same format ( one long string separated by a space.)

Example:

In:

test1
test2
test3

out:

test1 test2 test3
 
Can you show us what code you have so far?

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[noevil]
Travis - Those who say it cannot be done are usually interrupted by someone else doing it; Give the wrong symptoms, get the wrong solutions;
 
the first one:

#!/opt/perl5/bin/perl
use strict;
use warnings;
my $string;
open(FH, "< test.txt");
while (<FH>) {chomp; $string .= $_ . " "}
close FH;
$string .= "\n";
print $string;

the second one:

#!/opt/perl5/bin/perl
use strict;
use warnings;
my @files = glob "*";
my $string;
for (@files) {$string .= $_ . " "}
$string .= "\n";
print $string;

to output the string to a file:

open(FH, "> test.out");
print FH $string;
close FH;

 
Code:
use strict;
use warnings;

my @files = (<>);
chomp @files;
print join(' ', @files), "\n";
to invoke
Code:
perl myscript.pl input.txt > test.out

Steve

[small]"Every program can be reduced by one instruction, and every program has at least one bug. Therefore, any program can be reduced to one instruction which doesn't work." (Object::perlDesignPatterns)[/small]
 
How do i remove the path from being printed?

#!/opt/perl5/bin/perl
use strict;
use warnings;
my @files = glob "*";
my $string;
for (@files) {$string .= $_ . " "}
$string .= "\n";
print $string;
 
When I try your code I don't get a the path at all.. but I am on windows at the moment with no linux/unix to test on.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[noevil]
Travis - Those who say it cannot be done are usually interrupted by someone else doing it; Give the wrong symptoms, get the wrong solutions;
 
it's silly to slurp in the whole directory contents with the path only to remove the path. Use opendir() and readdir() if you want a list of all the file in the directoy. Otherwise use a glob or grep to target specific files in a directory.



------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top