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

print in file

Status
Not open for further replies.

mama12

Programmer
Oct 18, 2005
22
NL
Hi all,

I want to print all even numbers between -100 and 100,exclusef number -12 and 98.
my problem here is I can not print it in file.

best regards,

#!/usr/bin/perl -w

print "give a file name: ";
$fname = <STDIN>;
open FH, ">$fname" or die "Cant open File $!";

# with a for loop

$i = -102;
$y = -10;
$z = 100;
while($i <=-16) {
print $i++ ,"\n";
++$i;
}
while($y <=96) {
print $y++ ,"\n";
++$y;
}
while($z <=100) {
print $z ,"\n";
++$z;
}
print FH $z++,"\n";
close FH;

exit;
 
Code:
open FH, ">file.txt" or die "Can't open File $!\n";
for ($index=-100;$index<100;$index++) {
  if ($index % 2 == 0) {
    if (($index != -12) and ($index != 98)) {
      print FH "$index\n";
    }
  }
}

Paul
------------------------------------
Spend an hour a week on CPAN, helps cure all known programming ailments ;-)
 
You need to either put 'select FH;' after you upen the file (and don't forget to select STDOUT again when you're done printing to the file) or change all the print statements to 'print FH ...' - oh and you'll want to chomp the filename you get from the user.

Out of curiousity, why use all those loops? This is similar to Paul's code and includes the prin
Code:
my ($min, $max) = (-100, 100);
my %skip = (-12 => 1, 98 => 1);

print "File Name:";
chomp(my $file = <STDIN>);

open OUTPUT, "> $file" or die "Couldn't create $file\n$!";
for (my $i = $min; $i <= $max; $i++) {
    next if $skip{$i};
    next if $i % 2;
    print OUTPUT "$i\n";
}
close OUTPUT;
 
thanX allllllllL for ur help

regards
 
LOL! Where's that spell check? How, exactly, would I 'upen' a file? Yeah, so that probably should read: after you open the file.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top