rsennat has asked for the wisdom of the Perl Monks concerning the following question:

hi all,

how do i dynamically put the data into a file in /tmp??
my $userid = "rsennat"; #assume userid is set to a var my $string = $str1 . "," . $str2; system "echo $string" >> '/tmp/$userid';
so how to put the data dynamically in a file whose name is genrated during runtime.

thanks
rsennat

Replies are listed 'Best First'.
Re: put data in dynamic file
by serf (Chaplain) on Dec 13, 2005 at 09:33 UTC
    Presuming you're asking how to specify the name of the file? To do what you're doing here I would do:
    my $userid = "rsennat"; # assume userid is set to a var my $string = "$str1,$str2"; # NB: using double quotes so that the $userid is interpolated # Single quotes would protect the literal string like \$userid my $tmp_file = "/tmp/$userid"; open(TMPFILE, ">> $tmp_file") || die "Can't write to '$tmp_file': $!\n"; print TMPFILE $string; close(TMPFILE);
    You're better off opening a file and printing to it straight from Perl than relying on shelling out to echo or another command to do the same thing - shelling out (using system or *cough* backticks) uses another process, is less portable and takes away your script's full control over what you're doing.

    The only minus with doing it this way is that you have 3 lines of code instead of 1, but I'd take that hit any day for the improvement it makes to the efficiency, security, reliability and portability of the program!

      yes. "/tmp/$userid" - system command line gives error.
Re: put data in dynamic file
by davido (Cardinal) on Dec 13, 2005 at 09:39 UTC

    I doubt you need system for this.

    my $userid = 'rsennat'; my $string = "$str1,$str2"; open FH, '>>', "/tmp/$userid" or die "Cannot open $userid.\n$!"; print FH $string; close FH;

    Dave

Re: put data in dynamic file
by tphyahoo (Vicar) on Dec 13, 2005 at 09:38 UTC
    my $filename = "/tmp/$userid"; #use double quotes to interpolate, sing +le quotes are literal open OUT, ">> $filename" or die "couldn't open $filename for appending +"; print OUT, "This gets printed to the file\n"; close OUT;