in reply to Re^2: Contents of a file into a scalar
in thread Contents of a file into a scalar

Incorrect. I'm not talking about $string = read_line($QBF);. That line is probably working fine, assuming the file opened correctly (which you can't be sure of, because you didn't use "or die $!;". Debugging time is the most important time to have error reporting in place.

What I am talking about is this line: "print $string + "\n"; # doesn't print anything. (or prints "0")"

That line should not be adding $string to \n. It should be either concatenating with the 'dot' operator, or passing a list, with the comma operator. In other words, either of these would work:

print $string . "\n"; print $string, "\n";

You are using the addition operator. The addition operator applies numeric context to your "$string". Perl will convert that to the numeric value of "0", unless the string happens to begin with a number, or consists entirely of a number. Then it does the same thing to "\n". You said that "print $string + "\n";" prints "0". I'm saying the reason it prints zero is because both $string and \n, in the numeric context applied by "+" morph themselves into values of zero. Zero plus zero is zero, and that's what gets printed.

If you used either of the print statements I suggested, no such numification would occur, and assuming open worked ok, you would see the results you're after.

In C++ you would often overload '+' to deal gracefully with various data types. Unfortunately, + is also overloaded in C++ to concatenate std::string objects. Perl reserves "+" for math, and '.' for concatenation.

So in C++ you might say:

cout << my_string + "\n"; // Concatenation with newline. cout << my_string << std::endl; // Stream insertion with standard lin +e ending. cout << my_string << "\n"; // Stream insertion with newline.

In Perl, similar semantics are invoked with:

print $string . "\n"; # Concatenation with newline. print $string, $/; # List of items to print, with standard +line ending. print $string, "\n"; # List of items to print, with newline. # Or more conveniently... print "$string\n"; # Interpolation of a variable and newlin +e.

Dave