Path: utzoo!utgpu!news-server.csri.toronto.edu!clyde.concordia.ca!uunet!samsung!munnari.oz.au!frankland-river!pem From: pem@frankland-river.aaii.oz.au (Paul E. Maisano) Newsgroups: comp.lang.perl Subject: Re: Strange behavior with "local" Keywords: local bug Message-ID: <1364@frankland-river.aaii.oz.au> Date: 19 Mar 90 00:20:45 GMT References: <1363@frankland-river.aaii.oz.au> Organization: Australian AI Institute Lines: 56 In article <1363@frankland-river.aaii.oz.au>, pem@frankland-river.aaii.oz.au (Paul E. Maisano) writes: > Maybe I'm missing something but this seems like strange behaviour to me. > > ----------cut-here--------- > #!/usr/bin/perl > > $buf = "original value"; > > &buggy($buf); > print "buf=$buf\n"; > > sub buggy { > local($buf) = "new value"; > print "buf=$buf\n"; > $_[0] = $buf; > } > ----------cut-here--------- > > Running this produces: > buf=new value > buf=original value > > It seems that the value of the $buf variable is being restored before the > subroutine is exited. Sorry, I must be getting old... This is not strange behaviour at all. $buf is being restored *when* the subroutine returns. This is the documented behaviour of local. > I hope this is a bug, otherwise I have to be very careful about naming my > local variables. This is clearly not a bug in perl but a bug in my brain. However, this does demonstrate that due to the way local works you must be careful about naming your 'local' variables if you are modifying your arguments. The scenario is: You have a global variable called $buf. It calls a subroutine which alters $buf (by reference). [The subroutine knows nothing about the name of the variable.] The subroutine has a 'local' variable called $buf. When the subroutine exits, the old value of $buf is restored since we are no longer in the scope of the 'local'. Thus the new value of $buf is overwritten by the old value. This seems IMVHO to be a misfeature, if the names of local variables can affect the way the program runs. Isn't there any safer way to implement local variables. Static scoping ? I'd make some suggestions but I'm already too embarrassed by my last posting. ------------------ Paul E. Maisano Australian Artificial Intelligence Institute 1 Grattan St. Carlton, Vic. 3053, Australia Ph: +613 663-7922 Fax: +613 663-7937 Email: pem@aaii.oz.au UUCP: {uunet,mcsun,ukc,nttlab}!munnari!aaii.oz.au!pem