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

Hi. I'm writing a script which will read in a file and assign each line in the file to a variable. My problem is that I won't know the number of lines in advance. Is there a way to create the correct number of variables on the fly? It seems like there should be.

Ali

Fixed spelling in title - dvergin 2003-09-18

Replies are listed 'Best First'.
Re: dynamically created variables
by Zaxo (Archbishop) on Sep 18, 2003 at 22:17 UTC

    That's a perfect use for an array, my @lines = <IN>; that way you don't need to keep track of all those names, and the number of lines adjusts the array size automatically.

    After Compline,
    Zaxo

Re: dynamically created variables
by davido (Cardinal) on Sep 18, 2003 at 22:40 UTC
    Also if the file provides you with the names of each item being read in, you may want to use a hash. If so, you can do it like this:

    use strict; use warnings; my %hash; while (my $line = <DATA>) { my ($key,$value) = $line =~ /^\s*(.+?)\s*=\s*([^\s]+?)\s*$/; $hash{$key}=$value; } foreach ( keys %hash ) { print $_, "=", $hash{$_}, "\n"; } __DATA__ Test 1 = 10 Test 2 = 20 Test 3 = 30

    The preceding example strips leading and trailing whitespace from the keys and values stored in the file prior to inserting the key/value pairs into a hash for later use. The example breaks down if your keys or values actually contain '=' signs embedded within. I didn't use split because I wanted simpler control over the stripping of whitespace. The example also preserves whitespace if it occurs embedded within a key, but disallows it in the value. You could easily change that behavior.

    Hope this helps...

    Dave

    "If I had my life to do over again, I'd be a plumber." -- Albert Einstein

Re: dynamically created variables
by rdfield (Priest) on Sep 19, 2003 at 11:02 UTC
    Of course you can create variables on the fly:
    #use strict; #use warnings; my $counter = 0; while (<DATA>) { eval "\$a" . $counter++ . " = '$_';"; } print "$a0 $a1 $a2"; __DATA__ line 1 line 2 line 3

    rdfield

      DO NOT DO THIS

      This method is called "soft references". It is a capability of Perl, but there are very few reasons to actually use it. In nearly every isntance, hashes are much better, safer, and cleaner. There are many reasons why soft references don't compile under strict. Unless you know exactly why you shouldn't use soft references, DON'T USE SOFT REFERENCES!

      ------
      We are the carpenters and bricklayers of the Information Age.

      The idea is a little like C++ templates, except not quite so brain-meltingly complicated. -- TheDamian, Exegesis 6

      Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.