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

I still can seem to understand how to extract from arrays. Can someone help me to print the name only if it exists in the array. Thanks !
@system_name = qw(box1 box2); print "Please select a system to pull from\n"; $system1 = <STDIN>; chomp ($system1); $original_system = $system1; # save for later use $system1 =~ s/\W.*//; # get rid of everything after th +e first word $system1 =~ tr/A-Z/a-z/; # lowercase everything if (defined(@system_name = $system1)) { print "You have selected $system1\n"; }

Replies are listed 'Best First'.
Re: array confusion
by pelagic (Priest) on Jul 05, 2004 at 10:23 UTC
    if ( grep (m/^$system1$/ , @system_name)) {
    this might help ...

    pelagic

      Why use a regexp when you want equality?

      if ( grep { $_ eq $system1 } @system_name ) { ...

      Going back to the original question: This is a situation where a hash would be more appropriate:

      my %system_name = ( box1 => 1, box2 => 1 ); # ... if ( $system_name{$system1} ) { ...
      --
      edan

        so what is this line doing -er saying
        my %system_name = (box1 => 1, box2 => 1)
Re: array confusion
by graff (Chancellor) on Jul 05, 2004 at 14:24 UTC
    You have already gotten the answers you need, but let me point out one more issue that might cause trouble. You code says:
    $system1 = <STDIN>; # this is manual input from the keyboard #... $system1 =~ s/\W.*//; # what if input was " box1" (initial space)? #...
    You could simplify this as follows:
    ( $system1 = <STDIN> ) =~ s/^\W*(\w+).*/$1/s;
    (By including the "s" modifier on the substitution, you don't need to do "chomp", because the ".*" will match the final new-line.)

    But personally, I always prefer to get this sort of user input from the command line, via @ARGV. Programs that start up, then pause, print a prompt and wait until something gets typed at the keyboard are such a pain.

    my %systems = ( box1 => 1, box2 => 2 ); my $Usage = "Usage: $0 (" . join('|', sort keys %systems) . ")\n"; die $Usage unless ( @ARGV == 1 and $systems{$ARGV[0]} ); $system1 = lc( shift );
Re: array confusion
by neeraj (Scribe) on Jul 05, 2004 at 11:22 UTC
    @system_name = qw(box1 box2); print "Please select a system to pull from\n"; $system1 = <STDIN>; chomp ($system1); $original_system = $system1; # save for later use $system1 =~ s/\W.*//; # get rid of everything after th +e first word $system1 =~ tr/A-Z/a-z/; # lowercase everything foreach (@system_name) { print "You have selected $system1 \n" if ($_ eq $system1); }