![]() |
![]() | ![]() | ![]() | ![]() | ![]() | ![]() | ![]() |
| Welcome to Windows Vista Forums. Our forum is dedicated to helping you find solutions with any problems, errors or issues you are experiencing with Windows Vista. The Vista forum also covers news and updates and has an extensive Windows Vista tutorial section that covers a wide range of tips and tricks. |
| |||||||
![]() |
| |
| | #1 (permalink) |
| | Re: Empty output oddity in conjunction with foreach statement How about a variable setting that could be used to toggle how $nul get interpreted? "Duncan Smith" wrote: > On Mar 26, 3:06 pm, "Keith Hill" <r_keith_h...@mailhot.nospamIdotcom> > wrote: > > The following little nuance of PowerShell is kind of annoying. Say I have a function foo that may not output anything. OTOH it may output a series of say XML objects. I write some code to loop on the output I get from a call to this function e.g.: > > > > function foo { } > > > > $docs = foo > > foreach ($doc in $docs) { > > $_.SelectNodes('//compile') > > > > } > > > > This errors because foo returns nothing but something needs to be assigned to $docs. That something is $null and with the way the foreach statement is designed it will loop once on that scalar $null and I wind up getting this error: > > > > You cannot call a method on a null-valued expression. > > At line:2 char:19 > > + $_.SelectNodes( <<<< '//compile') > > > > Yet this seemingly harmless change causes the loop body to get skipped: > > > > foreach ($doc in foo) { > > $_.SelectNodes('//compile') > > > > } > > > > In this scenario since the function foo returns 'nothing' as opposed to $null the loop is completely skipped over. My problem with this is that it violates the principle of least surprise (at least for me). You wouldn't think that such a 'harmless' reorg of the code would change its behavior. > > > > I understand that having the foreach statement loop once on a scalar value is a good idea. However I wonder if the scalar value $null should be a special case and cause the foreach to skip the loop body. > > > > -- > > Keith > > There are probably other cases when the $null getting interpreted as > the integer 0 could be a good thing, if for example you were > populating an associative array and bumping an index-count. > > Could you maybe do something with checking $_ for equivalence with > $null and use a continue statement at the start of the loop? > > Regards, > > Duncan. > > |
My System Specs![]() |
![]() |
| Thread Tools | |
| |
Similar Threads | ||||
| Thread | Forum | |||
| Re: Oddity with ForEach-Object or is it me? | PowerShell | |||
| break from foreach statement | PowerShell | |||
| Re: Empty output oddity in conjunction with foreach statement | PowerShell | |||
| Sorting output from foreach | PowerShell | |||
| User Guide p.109 - Incorrect statement about foreach | PowerShell | |||