in reply to Re: Appending an array
in thread Appending an array

I need it to accept anyword and add it to the array. If someone enters webpage45 it would add to array such as: ('webpage1','webpage2','webpage45')

Then the next time the script is run someone enters page67 would then make the array look like this: ('webpage1','webpage2','webpage45','page67')

Please help me make this happen in my script.

Replies are listed 'Best First'.
(bbfu) (eq instead) Re3: Appending an array
by bbfu (Curate) on May 30, 2002 at 19:21 UTC

    boo_radley's method will work for anything (provided you use a variable instead of a literal 'webpage3'), except that you probably shouldn't use a regexp match as he did and just use eq instead, in case they, for example, type in 'webpage' (boo_radley's would match, and thus not add, even though it's technically different). Depends on how you want to handle those cases, though.

    #!/usr/bin/perl use warnings; use strict; our @data = qw(webpage1 webpage2); print "Webpage needed: "; # <STDIN> flushes output buffers chomp(my $response = <STDIN>); # <STDIN> instead of <> in case they # add command line arguments push @data, $response unless grep { $_ eq $response } @data; print "$_\n" for @data;

    (Update: Expounded upon why eq should probably be used instead of m//)

    bbfu
    Black flowers blossum
    Fearless on my breath
    Teardrops on the fire
    Fearless on my breath

      push @data, $response unless grep { $_ eq $response } @data;
      Please advise, I understand now that the push function adds to end of list but why is the grep on the response needed?
      Basically what is the grep { $_ eq $response } @data part doing??

        What grep does is go through the list and return a sublist of elements that (in this case) are equal to the element you're about to add. That sublist is then evaluated in boolean context by the unless: if the sublist is empty, it evaluates false, and the push takes place; if it's non-empty (which is to say, if $result appears in @data already), it evaluates true, and the push is stopped.

        In effect, the unless grep... means "unless we've already seen this result": it's there to prevent you from adding duplicates to @data. You could filter for it later on, but it'd be a pain, so pre-filtering it makes a lot of sense.



        If God had meant us to fly, he would *never* have given us the railroads.
            --Michael Flanders

Re: Re: Re: Appending an array
by the_0ne (Pilgrim) on May 30, 2002 at 19:22 UTC