On Apr 11, 2005 4:20 AM, Brent Clark <[EMAIL PROTECTED]> wrote: > Hi all > > If anyone has the time and / or the will to help me understand. > > I know how to create / use references for perl. But would why would you > use it. > And I think more importantly when. > > Im busy reading / learning the Oreilly Advanced Perl Programming book. > But for the likes of me I cant undertand when or why I would use it. > > Just something I was thinking. > > Kind Regards and thanks in advance > Brent Clark
Brent, In my mind, there are basically four general cases where you want references. The first is the one Ankur mentioned: you want to pass multiple lists to or from a subroutine. The second John and Johnathan covered: creating complext data structures. You can use references to create "deep" hashes or hashes of arrays, etc. You can also use them for things like circular linked lists (think of a website that cycles ads endlessly), or more complex thnks like binary trees. Two others: 1) You want a variable that is scoped to a subroutine (i.e. with "my"), but you don't want it destroyed when the subroutine exits--maybe it's a counting routine, and you want it to remember where ti left off counting. Or you want to keep a hash of e-mail adresses you've already mailed, or something like that. If you return a reference, the variable isn't destroyed. But it is still scoped to the subroutine, so if you've used a generic name like $email you can reuse that in another block without clobbering the value where you want it. 2) You want to pass a very large variable to or from a subroutine. Consider the following: my @newarray = foo(@bigarray) ; sub foo { my @array = @_ ; return @array ; } let's say that that @bigarray has a million email addresses. At the end of the subroutine, you'll have 2 million addresses eating up memory: @bigarray and @newarray. (You may briefly have something on the order of 3 million as @array gets copied out). If you use references, however, there's only one copy of the data in memory, a 50% savings. It's also a tremenous time savings for large data structures: copying an array requires at least one operation on every item in the array, which can really add up with large data sets. Creating a reference only requires a few pointer to be rearranged. HTH, --jay -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>