T.S.Ravi Shankar wrote: > Hi all : > > I have few arrays with names starting with "xyz_". After the initial > definitions I want to change values of a particular index of all arrays > whose names start with "xyz_". It would be cumbersome for me to do > something like : > > $xyz_blahblah[$index] = "ldfhdlf"; > $xyz_blooblooh[$index] = "dfhdlkfhdkf"; > $xyz_foofoo[$index] = 27; > > & so on... > > particularly when the number of arrays are many !! > > > Is there any method to do this easily ?? Or could I get the names of all > arrays with a particular starting string & then group them in a array > and proceed ?? >
depends on how you declare (global or lexical), you might go to the symbol table and ask for a certain type of variables (array, hash, scalar, etc) and update their values. the following assumes that you declare your variables as global with 'our' and update the third element (to have the value of 99) of all arrays whose name begines with 'xyz': #!/usr/bin/perl -w use strict; #-- #-- the following 3 arrays are declared with 'our' which makes #-- them global and thus visible in the symbol table. the third #-- element of those arrays will be updated to have the value of 99 #-- our @xyz_var1 = 1 .. 5; our @xyz_var2 = 2 .. 6; our @xyz_change_me = 12 .. 16; #-- #-- the following is not updated: #-- #-- @dont_change_me: because it doesn't start with xyz #-- %xyz_dont_change_me: because it's a hash, not array #-- $xyz_dont_change_me: because it's a sclar, not array #-- @xzy_not_global: because it's declared with 'my' which makes it lexical #-- our @dont_change_me = 7 .. 11; our %xyz_dont_change_me = 50 .. 53; our $xyz_dont_change_me = 100; my @xzy_not_global = 17 .. 21; #-- #-- this asks the symbol table for all globol variables declared so far #-- and update the array's 3rd element to 99 #-- $::{$_}->[2] = 99 for(grep {/^xyz/} keys %::); #-- #-- demo to show their values are indeed changed #-- print join(" ",@xyz_var1),"\n"; print join(" ",@xyz_var2),"\n"; print join(" ",@xyz_change_me),"\n\n"; #-- #-- demo to show that this is not changed #-- print join(" ",@dont_change_me),"\n"; print join(" ",@xzy_not_global),"\n"; __END__ prints: 1 2 99 4 5 2 3 99 5 6 12 13 99 15 16 7 8 9 10 11 17 18 19 20 21 generally, this is a poor approach especially if you are new to Perl. you might accidentally change something that you are not intended to change. other disadvantages include: * it's slow because it walks the entire symbol table each time it's called. you can improve this by caching the variables in a hash but you must be careful that you don't declare more arrays after you cache them because the cache version won't see those. * it's dangerous because we might change something that you don't really want to change. this is especially important if you are new to Perl. * if your arrays are declared with 'my', they won't be changed at all. david -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]