in reply to local and global variable?

There are serious flaws with this code.

For example, my @species = split "//", $list;. The @species array will contain each letter of $list (a split on the null string is every letter of the original string).

update: Opps... @species = split(//,$list) is not @species = split("//",$list). A cross-eyed booboo on my part. Sorry.

@tree will contain the lines returned from the "backtick" command in the subroutine. The foreach loop is the main program as presented.

my @tree_array; # my @species = split "//", $list; # would: # foreach my species ('a','b','c') {} work? I think not? foreach my $species(@species) { my @tree = edit($species); push @tree_array, [@tree] if @tree; print @tree if @tree; } ## do you want to use @tree here? ## if so, then ...you need to use the array ## of the @tree results... foreach $tree_ref (@tree_array) { print "@$tree_ref\n"; } sub edit { my ($species) = shift; #slightly faster when just one arg my ($pid) = ($species =~ /RANK.*?subspecies.*?PARENT ID.*?(\d+)/); ### or ### ## look for "PARENT ID", then anything until there are ## one or more digits my ($pid) = ($species =~ /PARENT ID.*?(\d+)/); if (defined $pid) { return `getz "[taxonomy:$pid]" -e`; } return undef; }
Feel free to modify the above code, show a runnable example of your problem.

Replies are listed 'Best First'.
Re^2: local and global variable?
by AnomalousMonk (Archbishop) on Aug 22, 2011 at 11:23 UTC
    ... my @species = split "//", $list;. The @species array will contain each letter of $list (a split on the null string ...

    Splitting on  "//" does not split on the null string, but rather on the literal sequence of two forward-slash characters.

    >perl -wMstrict -le "my $s = 'foo//bar//baz'; my @species = split qq{//}, $s; printf qq{'$_' } for @species; " 'foo' 'bar' 'baz'
      my booboo corrected above. Thanks for pointing this mistake out.

      It was an accident waiting to happen. This is one reason I always make it clear in my code that the first argument of split is a regular expression pattern, not a string.

      my @species = split m{//}, $list;