Hello again alokranjan,
Now I would like to print the name of file itself (means country name) by passing the name of city to a subroutine. But value is not changing. (Emphasis added.)
I notice that you use strict but not warnings. When I run your code with perl -wc I get:
23:34 >perl -wc 1342_SoPW.pl Variable "$name" will not stay shared at 1342_SoPW.pl line 39. 1342_SoPW.pl syntax OK 23:35 >
And with diagnostics:
23:35 >perl -Mdiagnostics -wc 1342_SoPW.pl Variable "$name" will not stay shared at 1342_SoPW.pl line 39 (#1) (W closure) An inner (nested) named subroutine is referencing a lexical variable defined in an outer named subroutine. When the inner subroutine is called, it will see the value of the outer subroutine's variable as it was before and during the *f +irst* call to the outer subroutine; in this case, after the first call t +o the outer subroutine is complete, the inner and outer subroutines will + no longer share a common value for the variable. In other words, the variable will no longer be shared. This problem can usually be solved by making the inner subroutine anonymous, using the sub {} syntax. When inner anonymous subs tha +t reference variables in outer subroutines are created, they are automatically rebound to the current values of such variables. 1342_SoPW.pl syntax OK 23:36 >
This explains why the value is not changing: on the first call to getCountry the variable $name is set to “NY” in both getCountry and txtsearch. But on the second call, $name becomes “London” in getCountry but remains “NY” within txtsearch. This is easily confirmed by adding print statements at appropriate points within these subs.
Moral: always use warnings !
Hope that helps,
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
In reply to Re: Grep a word and print the filename
by Athanasius
in thread Grep a word and print the filename
by alokranjan
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |