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

Hi, Sorry again for coming back with a similar bit of code. I get the message: Use of uninitialized value in substitution (s///) at transform.pl line 19, <INPUT> line 78.
if ($line =~ /^%(.{1,100})$/){ s/\s//g; $name = $1; print "EEEEEEEEEEEEEEEEEEEEEEEEEEEE: $name\n"; } $outfile = "outfile['$name'].txt"; open (OUTFILE, "+>>$outfile");
I would like to remove white space for the variable $name that is used to name the output files. Can any monks offer support and guidance to a man who is new to the cloth?

Replies are listed 'Best First'.
Re: substitution (s///)
by Enlil (Parson) on Dec 01, 2002 at 19:36 UTC
    What the error is telling you is that $_ is uninitialized at the line s/\s//g, which is the variable you are doing the substitution on, since you have not given it another (e.g. $variable =~ s/\s//g;

    I think what you want is probably stomething like:

    if ($line =~ /^%(.{1,100})$/){ $name = $1; $name =~ s/\s//g; #this is the variable I think you want to r +emove spaces from. print "EEEEEEEEEEEEEEEEEEEEEEEEEEEE: $name\n"; } $outfile = "outfile['$name'].txt"; open (OUTFILE, "+>>$outfile");

    On a side note unless the spaces will be in the center of the variable $name you might just want to anchor the search to the beginning (using ^)and the end (using $) as it is faster.

    -enlil

Re: substitution (s///)
by spurperl (Priest) on Dec 02, 2002 at 06:56 UTC
    Whether you want to perform substitution on $line or $name is unclear (it is probably $name though), but the substitution expects the $_ variable to be initialized.

    When you use s/// (and many other Perl constructs) in "void context" - w/o arguments, it assumes the $_ var is its argument. The regext in the if() doesn't insert anything into $_, so you get the warning.

    It's best to be explicit... supply s/// with the var you want the substitution on, then you won't have to scratch your head for too long trying to understand bugs like this.

      A nitpick: context refers to the calling environment and how any return values will be assigned. If those results are not utilized to populate a single variable (scalar context) or a list of variables (list context) but are merely tossed away, then the context is void (cf. wantarray).

      In this case, the substitution does occur in void context, however that's not why $_ is assumed to be the target; rather it's because the subroutine doesn't explicitly tell s/// what to operate on and thus perl fills that value in for you.