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

Can't read from file???

Status
Not open for further replies.

karyn1617

Programmer
Feb 17, 2005
6
US
Here is a code snippet

open(SOURCE, $input) || die "Cannot Open $input: $!\n";

while( <SOURCE> )
{

chomp($File = $_);
open(FILE, $File) || die "Cannot Open $File: $!\n";
$inputString = <FILE>;
print "$inputString\n";

But for some reason the inputString is empty, even though I made sure the file it was reading is not...what's going on??
I am new to Perl please help!
 
Place double quotes for the file name in open function.
 
Ok I figured out I was only reading the first line, but how do I read the whole file into a string? Or is it only possible to read the whole fine into an array of lines??
 
Instead of scalar, use an array like this.

Code:
@inputString = <FILE>;
 
reading into an array is easy, but you can use what is often called slurp mode and read the whole file into a scalar:

Code:
open(SOURCE, $input) || die "Cannot Open $input: $!\n";

while( <SOURCE> )
{
 
   chomp($File = $_);
   open(FILE, $File) || die "Cannot Open $File: $!\n";
   $inputString = do { local $/; <FILE> };
   print "$inputString\n";
 
Hi karyn1617

Maybe this will help


#--------- Begin sub do_change_theme -----


##################################
## do_change_theme
##################################
sub do_change_theme
{

if ( $FORM{ "edit_theme" } eq "Default" )
{
$source_file = qq~./themes/Default.pm~;
}
elsif ( $FORM{ "edit_theme" } eq "Cool Blue" )
{
$source_file = qq~./themes/Cool_blue.pm~;
}
elsif ( $FORM{ "edit_theme" } eq "Spring Green" )
{
$source_file = qq~./themes/Spring_green.pm~;
}

$target_file = qq~./Sm/Sm_css.pm~;

open(FH, "<", $source_file);

seek(FH, 0, 0 );





###### Get the entire file into memory (let's hope it's small!)

local $_;






my @lines = split /\015\012?|\012|\025|\n/, join( '', <FH>);

$FORM{"the_class"} = "";

foreach ( @lines )
{
$FORM{"the_class"} = $FORM{"the_class"} . $_ . "\n";
next;
}

close FH;



if( length($FORM{'the_class'}) == 0 )
{
$the_error = qq{Whoops - I cannot save a blank page.};
$oMy->new_error_form($the_error);
}
else
{

open(FH, ">", $target_file);
print FH $FORM{"the_class"};

close FH;
}

if (
$! eq "Bad file descriptor"
|| $! eq "Inappropriate ioctl for device"
)
{

}
else
{
$the_error = qq~Copy failed: $!~;

$oMy->new_error_form( $the_error, "kart_main.pl" );

}
}

#--------- End sub do_change_theme -----

Regards,

LelandJ

Leland F. Jackson, CPA
Software - Master (TM)
Nothing Runs Like the Fox
 
THANKS GUYS!!!!

I ended up using $inputString = do { local $/; <FILE> };
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top