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

how to send cat results of file to a variable

Status
Not open for further replies.

bubsgt95

Programmer
Feb 21, 2003
6
US
i am trying to write a script to log on to every server and cat the contents of a file.. and then print that to a log file on my starting point server.

is there anyway i can send the results of "cat /etc/sudoers" to a variable? so i can open a logfile.. and just say print $log or something of that sort?
 
Code:
log=`cat sudoers`
Make sure those are backticks, and not apostrophes (it's usually the key with the tilde).
 
That costs you an extra process per file which could become a huge overhead. If you're doing a lot you probably want to declare

[tt]sub cat {
local $/ = undef; # enabled slurp mode within this sub
my $cat;
foreach my $f (@_) { # can accept multiple files - will just concatenate them
open( F, $f ) or die "$0: $f: $!";
$cat .= <F>;
close( F ) or die &quot;$0: $f: $!&quot;;
}
return $cat;
}[/tt]

and then you can just say

[tt]$log = cat '/etc/sudoers';[/tt]

You probably also want to look at File::Find which allows you easily to walk filesystems. &quot;As soon as we started programming, we found to our surprise that it wasn't as
easy to get programs right as we had thought. Debugging had to be discovered.
I can remember the exact instant when I realized that a large part of my life
from then on was going to be spent in finding mistakes in my own programs.&quot;
--Maurice Wilk
 
If you assign the output of a command with backticks to a scalar, you get all the output (including newlines) in one long scalar value, which is fine if you're just going to print it. If you want more control over it or need line-by-line processing, you can assign it to an array, and it'll split the output on the input record separator $/ (defaults to \n).
Code:
@a = `ls -l`;
print scalar @a;
generates 37, the number of lines (and files) in the output.
Code:
$a = `ls -l`;
print length $a;
[code]
generates [b]2045[/b], the number of characters in all the output.

Removing the [code]scalar
and
Code:
length
from the print statements will cause both to generate the same output. ----------------------------------------------------------------------------------
...but I'm just a C man trying to see the light
 
Wow, I was late on this one. A guy can't take more then five minutes to come up with a reply. Sorry for the repeated info. :) ----------------------------------------------------------------------------------
...but I'm just a C man trying to see the light
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top