On Saturday, June 7, 2003, at 07:36 PM, Harry Putnam wrote:

Consider this code:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#!/usr/local/bin/perl -w
$num = 234;
$line1 = "$num some text here";
$line2 = "$num ";  ## note the space after.

@array = ("$line1","$line2");

for (@array){
    $trimmed_line = (split(/^$num /,$_))[1];

Maximum number of elements this could return is one, since you're 'splitting' it on anything that BEGINS with 234. All you can get back is, what came after, or the whole thing, if there was no match. Since you're asking for the second element of the returned list (index 1), you're getting nothing. When you try to use it later, it's an unitilalized value and triggers the proper warning. This is probably not a good use for split().


# ($trimmed_line = $_) =~ s/^$num //;

This, on the other hand is a search/replace and probably works exactly as you expect. The lines are preforming two different operations, thus the different results.


  print "\$trimmed_line = <$trimmed_line>\n";
}
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Returns:
 ./sptest
 $trimmed_line = <some text here>
  Use of uninitialized value in concatenation (.) or string
  at ./sptest line 13.
 $trimmed_line = <>

But if you use the commented line instead of the split line:

  ./sptest
  $trimmed_line = <some text here>
  $trimmed_line = <>


Either way, $line2 = ''; but the split way throws the error message.


Why is that?

Hopefully I shed at least a little light.


James

P.S. I realize your example is pretty trivial, but good habits take practice. 'use strict' is probably a good idea.


-- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]



Reply via email to