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

Hey monks, I can't figure out what to do to alleviate the error uninitialized value in substitution using the following:
#!/usr/bin/perl -w # print "Please put in the username for which you want to setup a virtua +l host:\n"; my $user = <STDIN>; my @fields = (); my $fields = (); open TPL, "vh_template.tpl"; my @vhost = <TPL>; close TPL; foreach my $vhost(@vhost){ if ($vhost =~ /^ServerName/){ @fields = split /\./, $vhost; $fields = @fields; s/$fields\[0\]/$user/; #this line generates the error print "$fields[0]\n"; } }
Thanks for your help! John

Replies are listed 'Best First'.
Re: uninitialized value in substitution
by ihb (Deacon) on Sep 09, 2004 at 19:40 UTC

    You're implicitly binding the s/// to $_ which isn't initialized. s/$fields\[0\]/$user/; is really $_ =~ s/$fields\[0\]/$user/;.

    ihb

    Read argumentation in its context!

Re: uninitialized value in substitution
by bobf (Monsignor) on Sep 09, 2004 at 19:46 UTC

    Your s/// is defaulting to use $_, which is not initialized. If I understand what you're trying to do, use $vhost =~ s/$fields[0]/$user/. Note that you shouldn't escape the brackets for the array index.

    HTH
Re: uninitialized value in substitution
by ikegami (Patriarch) on Sep 09, 2004 at 19:50 UTC

    First, you never specify in your code against what you're matching, and you never give a value to $_ (the variable against which matching is done by default). I can't fathom what the line giving the error is trying to do (matching against any of the variables in the snippet woulnd't make sense), so we don't know how to fix this.

    Second, my $fields = (); is the same as my $fields = undef;, and in the regular expression, you're refering to this variable instead of the first element of @fields as you probably intended. If you want to match what's in the first element of @fields, try: s/$fields[0]/$user/. Of course, that should probably really be: s/\Q$fields[0]\E/$user/ since @fields holds simple strings, not regexps.

Re: uninitialized value in substitution
by mayhem (Hermit) on Sep 09, 2004 at 19:36 UTC
    You should chomp($user) in there somewhere and the line your getting an error on... why don't you just do
    $fields[0] = $user;
    That should work if i understand what you are trying to do..