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

Good Morning Esteemed Monks!

My question has to do with auto increments and I think I am missing something very simple as when I add rows to my file the ID should go up by 1 when each new entry is added correct? Please refer to my code below and point me in the right direction as to what I am missing. Thanks in advance!



my $id = 1; my $output="data.txt"; open(DAT,">>$output") || die("Cannot Open File"); print DAT ($id++); print DAT (":"); print DAT ($name); print DAT (":"); print DAT ($number); print DAT (":"); print DAT ($address); print DAT (":"); print DAT ($phone); print DAT (":"); print DAT ($email); print DAT ("\n"); close (DAT);

Replies are listed 'Best First'.
Re: auto increment
by choroba (Cardinal) on May 05, 2015 at 13:08 UTC
    You only increment $id once. Before incrementing it, you set it to 1. If you want to add an entry to a file, you have first to read the last entry from the file, get its id, increment it, and then write the new entry.
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

      Exactly. Like this, for example:

      use feature 'say'; my $output = "data.txt"; open(DAT, '+<', $output) || die("Cannot Open File"); my $id; while (<DAT>) { ($id) = m/\A(\d+):/; } say DAT join ':', ++$id, $name, $number, $address, $phone, $email; close(DAT);

        Better yet:

        use feature 'say'; my $output = "data.txt"; open(DAT, '+<', $output) || die("Cannot Open File"); my $line; $line = <DAT> until eof DAT; my ($id) = $line =~ m/\A(\d+):/; say DAT join ':', ++$id, $name, $number, $address, $phone, $email; close(DAT);

        This way, the regular expression is only executed once - on the last line.

        Sorry for the double post, I can't edit my comments (not enough powers yet).

Re: auto increment
by pme (Monsignor) on May 05, 2015 at 13:30 UTC
    You can read the whole file into the memory (@file) and take the id from the very last line.
    open(DAT, "<$output") || die("Cannot Open File"); my @file = <DAT>; close DAT; my $id = (split(':', $file[-1]))[0]; $id++; print "$id\n";
Re: auto increment
by edimusrex (Monk) on May 05, 2015 at 14:39 UTC
    I would set the ID number equal to the line number + 1 by reading the file into an array first. Something like this would do the trick. Each to you executed the script the ID should increment by 1.

    my $file = "data.txt"; open FILE, "<$file"; @lines = <FILE>; close FILE; $id = @lines; $id++; open DAT, ">>$file"; print DAT ("${id}:${name}:${number}:${address}:${phone}:${email}\n"); close DAT;
      You don't need to store all the lines to count them. You can just count them when reading them:
      my $count = 0; $count++ while <FILE>;

      In fact, Perl already does that.

      1 while <FILE>; my $count = $.;
      لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
        Ah, that's a nice tip. Thanks